Opscraft
Docker · Lesson 3 of 11 · 5 min read

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

  • ENTRYPOINT is the executable. CMD provides default arguments (or the whole command if there's no ENTRYPOINT).
  • docker run image arg1 arg2 replaces CMD; --entrypoint replaces ENTRYPOINT.
  • In Kubernetes, command: overrides ENTRYPOINT and args: 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"] — runs node directly as PID 1. It receives SIGTERM from docker 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 "$@"
Enlarge diagramCMD ["node", "server.js"]CMD node server.jsnode is PID 1SIGTERM reaches the appGraceful shutdown works/bin/sh -c is PID 1; node is its childsh does not forward SIGTERMSIGKILL after the timeout: exit 137, droppedrequests
Figure 1. Exec form vs shell form. With the shell form, sh is PID 1 and usually does not pass SIGTERM on, so the app is killed hard after the grace period.
Swipe sideways to see all of it, or tap to open it full screen.

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:

  1. Base image and OS packages
  2. Dependency manifests (package.json, go.mod, requirements.txt, pom.xml) and dependency install
  3. Application source
  4. Build/compile

Copying the entire source before npm ci means every code change reinstalls all dependencies.

Enlarge diagramGOOD ORDERBAD ORDERFROM node:22-slimCOPY package*.json .RUN npm ciCOPY . .RUN npm run buildFROM node:22-slimCOPY . .RUN npm ciRUN npm run buildevery code change reinstalls all packagesgreen = reused from cacheamber = rebuilt after a code changered = slow step rebuilt for nothing
Figure 2. Layer caching: once one step changes, every step after it rebuilds. Put rarely changing steps first.
Swipe sideways to see all of it, or tap to open it full screen.

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/*