Dockerfile Instruction Reference
A comprehensive reference of core Dockerfile instructions, execution models, and container runtime behaviors.
Core Instructions Matrix
| Instruction | Purpose | Execution Stage | Best Practice |
|---|---|---|---|
FROM |
Sets the base image. Must be the first instruction. | Build time | Use minimal, official tags (e.g. alpine:3.20, python:3.12-slim, distroless). |
WORKDIR |
Sets working directory for subsequent instructions. | Build & Run time | Always use absolute paths (WORKDIR /app). Avoid chaining cd. |
COPY |
Copies files from host build context to container filesystem. | Build time | Prefer COPY over ADD. Only use ADD for automatic tar extraction. |
RUN |
Executes commands and commits a new layer to the image. | Build time | Combine commands (&&) and clean package caches in the same layer. |
ENV |
Sets persistent environment variables. | Build & Run time | Group variables to reduce layers. |
ARG |
Defines build-time variables (not persisted in the final image). | Build time only | Ideal for version numbers, Git commit hashes, and build targets. |
EXPOSE |
Documents network ports the container listens on. | Metadata only | Informs operators which ports to map; does not publish ports automatically. |
USER |
Sets the UID/GID to run subsequent commands and container processes. | Build & Run time | Avoid running as root. Specify a non-root user (e.g. USER 10001:10001). |
VOLUME |
Creates a mount point directory for persistent or shared storage. | Run time | Useful for databases and stateful paths; data bypasses the union filesystem. |
HEALTHCHECK |
Defines a command to test whether the container is healthy. | Run time | Use curl or custom ping commands (HEALTHCHECK --interval=30s CMD ...). |
ENTRYPOINT |
Configures the default executable that runs when the container starts. | Run time | Use exec form: ENTRYPOINT ["/bin/app"]. |
CMD |
Default arguments passed to ENTRYPOINT, or default standalone command. |
Run time | Overridden by arguments passed to docker run. |
ENTRYPOINT vs. CMD
Understanding the interaction between ENTRYPOINT and CMD is critical for designing reusable container images:
graph TD
CLI["docker run myimage foo bar"] --> Eval{"How is Dockerfile defined?"}
Eval -- "ENTRYPOINT only: ['app']" --> Run1["Runs: app foo bar"]
Eval -- "CMD only: ['app', 'default']" --> Run2["Runs: foo bar (CMD replaced)"]
Eval -- "ENTRYPOINT + CMD" --> Run3["Runs: app foo bar (CMD acts as default args)"]
1. The Exec Form (Preferred)
# Exec form runs binary directly without a shell wrapper (PID 1 receives SIGTERM signals correctly)
ENTRYPOINT ["/usr/bin/python3"]
CMD ["app.py", "--port", "8080"]