A Dockerfile is a plain text recipe: each line is an instruction, executed top to bottom, and most of them add a layer to the image. Write it well and your builds take seconds and produce small, safe images. Write it carelessly and every build reinstalls everything.
The essential instructions
| Instruction | Purpose |
|---|---|
FROM | Base image to start from; every Dockerfile begins with it |
WORKDIR | Set (and create) the working directory for the next instructions |
COPY | Copy files from the build context into the image |
RUN | Run a command at build time, such as installing packages |
ENV | Set an environment variable for build steps and the running container |
ARG | A build-time variable, passed with --build-arg |
EXPOSE | Document the port the app listens on (it does not publish it) |
USER | Run the next instructions and the container as this user |
HEALTHCHECK | A command Docker runs to decide if the container is healthy |
CMD / ENTRYPOINT | What runs when the container starts |
A complete Dockerfile
Here is a production-style Dockerfile for a Python web API:
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app
# Dependencies first: this layer is reused until requirements.txt changes.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Application code last: it changes on every commit.
COPY . .
RUN useradd --create-home --uid 10001 app
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
$ docker build -t api:1.0 .
[+] Building 18.4s (11/11) FINISHED
$ docker run -d --name api -p 8000:8000 api:1.0
$ docker ps --format '{{.Names}}: {{.Status}}'
api: Up 45 seconds (healthy)
Order instructions for the build cache
Docker reuses a cached layer as long as the instruction and its inputs did not change. The moment one layer changes, every layer after it is rebuilt. So put what changes rarely at the top and what changes often at the bottom.
$ echo "# tweak" >> main.py
$ docker build -t api:1.1 .
=> CACHED [2/6] WORKDIR /app
=> CACHED [3/6] COPY requirements.txt .
=> CACHED [4/6] RUN pip install --no-cache-dir -r requirements.txt
=> [5/6] COPY . .
[+] Building 1.9s (11/11) FINISHED
Changing the code only reran the last steps; the slow dependency install came from cache. If COPY . . came before pip install, every code change would reinstall all dependencies.
Tip: a .dockerignore file keeps .git, node_modules, virtual environments and secrets like .env out of the build context. Smaller context means faster builds and no leaked credentials.
CMD versus ENTRYPOINT
CMDsets the default command; anything you put after the image name indocker runreplaces it.ENTRYPOINTsets a fixed executable;docker runarguments are appended to it.
Always use the exec form with square brackets. The shell form (CMD uvicorn main:app) wraps your app in /bin/sh -c, so the shell receives SIGTERM instead of your app, and docker stop has to wait for the SIGKILL timeout.
ENTRYPOINT ["python", "-m", "mytool"]
CMD ["--help"]
With this pair, docker run mytool shows the help, and docker run mytool sync --dry-run runs python -m mytool sync --dry-run.
Multi-stage builds
Compilers and build tools are needed to build your app, not to run it. A multi-stage build uses one stage to compile and copies only the result into a minimal final stage:
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/server ./cmd/server
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
USER nonroot
ENTRYPOINT ["/server"]
$ docker build -t server:1.0 .
$ docker images server
REPOSITORY TAG IMAGE ID CREATED SIZE
server 1.0 5d2a8c1f9e7b 10 seconds ago 9.8MB
The final image holds only the binary and a tiny runtime: under 10 MB instead of the roughly 900 MB Go toolchain image.
Build arguments and secrets
ARG values customize a build, for example a version label:
$ docker build --build-arg APP_VERSION=1.4.2 -t api:1.4.2 .
Never pass passwords or tokens with ARG or ENV: they end up readable in the image history. Use BuildKit secrets instead, which are mounted only while one RUN step executes:
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci
$ docker build --secret id=npm_token,env=NPM_TOKEN -t web:1.0 .
Exercise
A Dockerfile has ENTRYPOINT ["python", "app.py"] and CMD ["--port", "8000"]. What runs with docker run myapp --port 9000?
Show answer
Answer: C. Arguments after the image name replace CMD, and CMD is always appended to ENTRYPOINT. That makes ENTRYPOINT the fixed command and CMD its overridable default arguments.
Key takeaways
- Order instructions from least to most frequently changed to get the most from the cache.
- Use the exec form of
CMDandENTRYPOINTso your app receives stop signals. - Multi-stage builds ship only what runs, often shrinking images by 90% or more.
- Run as a non-root
USER, and pass secrets with BuildKit secret mounts, neverARGorENV.
FAQ
What is the difference between COPY and ADD?
ADD can also download URLs and unpack local tar archives. That extra magic surprises people, so prefer COPY unless you specifically need archive extraction.
Should I combine RUN commands with &&?
Combine commands that belong together, especially install and cleanup (apt-get update && apt-get install ... && rm -rf /var/lib/apt/lists/*), so temporary files never land in a layer. Do not merge unrelated steps, or you lose caching.
Does EXPOSE make my port reachable?
No. EXPOSE is documentation and a default for some tools. You still publish the port at run time with -p.