Writing Dockerfiles properly
The instructions
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS base # base image; pin a specific version
LABEL org.opencontainers.image.source="https://github.com/acme/orders"
ARG APP_VERSION=dev # build-time variable
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 # runtime env, baked into the image
WORKDIR /app # creates and cds; avoid RUN cd
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY src/ ./src/
RUN useradd -r -u 10001 app
USER 10001 # numeric UID works with runAsNonRoot checks
EXPOSE 8000 # documentation only
HEALTHCHECK --interval=30s --timeout=3s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
ENTRYPOINT ["python", "-m", "src.server"]
CMD ["--workers", "4"]
| Instruction | Notes |
|---|---|
FROM |
Every stage starts with one; FROM scratch is an empty base |
RUN |
Executes at build time; creates a layer |
COPY / ADD |
ADD also fetches URLs and auto-extracts local tarballs — prefer COPY for predictability |
ARG |
Build-time only; an ARG before FROM is only usable in FROM lines |
ENV |
Persists into containers; visible in docker inspect |
WORKDIR |
Sets the working directory for later instructions and at runtime |
USER |
Drops root for later instructions and at runtime |
EXPOSE |
Metadata; publishing happens with -p at run time |
VOLUME |
Declares a mount point; data there bypasses the layer |
HEALTHCHECK |
Docker marks the container healthy/unhealthy (Kubernetes ignores it — it uses probes) |
ENTRYPOINT / CMD |
What runs; see below |
ENTRYPOINT vs CMD
ENTRYPOINTis the executable.CMDprovides default arguments (or the whole command if there's no ENTRYPOINT).docker run image arg1 arg2replaces CMD;--entrypointreplaces ENTRYPOINT.- In Kubernetes,
command:overrides ENTRYPOINT andargs:overrides CMD.
| ENTRYPOINT | CMD | docker run img runs |
docker run img x runs |
|---|---|---|---|
| — | ["nginx","-g","daemon off;"] |
nginx -g daemon off; | x |
["python","app.py"] |
["--port","80"] |
python app.py --port 80 | python app.py x |
Exec form vs shell form
- Exec form
CMD ["node", "server.js"]— runsnodedirectly as PID 1. It receives SIGTERM fromdocker stop/ Kubernetes. - Shell form
CMD node server.js— runs/bin/sh -c "node server.js". The shell is PID 1; it typically doesn't forward SIGTERM, so the app is SIGKILLed after the grace period — no graceful shutdown, dropped requests.
For entrypoint scripts that do setup, end with exec "$@" so the app replaces the shell as PID 1:
#!/bin/sh
set -e
envsubst < /etc/app/config.tpl > /etc/app/config.yaml
exec "$@"
Build context and .dockerignore
docker build . sends the build context (the directory) to the builder. A huge context (node_modules, .git, datasets) slows every build and can leak secrets into images via COPY . ..
# .dockerignore
.git
node_modules
**/*.log
.env
*.pem
dist
How layer caching decides
For each instruction, the builder reuses the cached layer if the instruction text is the same and every previous layer was a cache hit. For COPY/ADD, it also checksums the files copied. Once one step misses, every later step rebuilds. Hence the golden rule — order from least to most frequently changing:
- Base image and OS packages
- Dependency manifests (
package.json,go.mod,requirements.txt,pom.xml) and dependency install - Application source
- Build/compile
Copying the entire source before npm ci means every code change reinstalls all dependencies.
A RUN apt-get update cached weeks ago never refreshes, which is why update and install must be in the same RUN:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*