Lesson 9 of 24Real apps
Docker in Production
Ship small, secure images that shut down cleanly, report their health, and are built and pushed by CI.
An image that works on your laptop is not yet ready for production. In production it must be small enough to deploy fast, hold no secrets, run without root, stop cleanly when the platform asks, and be traceable back to the exact commit it came from. These are the details that separate "I used Docker" from "I ran Docker in production" in an interview.
Choose a small base image
The base image is usually most of your image, and every package in it is something that can have a vulnerability. Fewer packages means a smaller attack surface.
| Base | Size (about) | What is inside | Tradeoffs |
|---|---|---|---|
python:3.13 | 1 GB | Full Debian, compilers, git, curl | Easy to build in; far too much to ship |
python:3.13-slim | 120 MB | Minimal Debian + Python | The sensible default. glibc, so wheels just work |
python:3.13-alpine | 50 MB | Alpine Linux + Python | Tiny, but uses musl libc: some packages compile from source, and builds can get slower and bigger |
Distroless (gcr.io/distroless/...) | 50 to 70 MB | Only the runtime and its libraries, no shell, no package manager | Very small attack surface; harder to debug |
scratch | 0 MB | Nothing at all | Only for fully static binaries (Go, Rust) |
For Python and Node, start with -slim and a multi-stage build. Move to distroless or a hardened image when your security requirements call for it.
python:3.13: everything. Hundreds of packages, so scanners report many CVEs, most in tools you never call.
Run as a non-root user
By default the process in a container runs as root (user ID 0). Namespaces limit what it can do, but if an attacker escapes the app, being root inside makes every next step easier. Create a user and switch to it before CMD.
FROM python:3.13-slim
WORKDIR /app
RUN useradd --create-home --uid 10001 app
COPY --from=build --chown=app:app /app /app
USER app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Official Node images ship a node user and distroless images have a nonroot variant, so you only need USER. At run time you can go further with --read-only (the root filesystem becomes read-only) and --cap-drop ALL (drop extra kernel privileges).
Never put secrets in an image
Anyone who can pull your image can read every layer. docker history shows the commands, docker inspect shows every ENV, and any layer can be extracted with tar. Deleting a file in a later layer only hides it.
COPY .npmrc . (it contains a private registry token), then RUN npm ci, then RUN rm .npmrc. Is the token in the pushed image?For build-time secrets, BuildKit mounts them into a single RUN step without writing them to any layer:
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm cidocker build --secret id=npmrc,src=$HOME/.npmrc -t web:1.0 .Runtime secrets (database passwords, API keys) are passed by the platform when the container starts: environment variables injected from AWS Secrets Manager, Kubernetes Secrets, or your host's secret store. Never ENV API_KEY=... in a Dockerfile.
Pin versions and scan
Reproducible builds need fixed inputs:
- Pin the base image to a specific version (
python:3.13.9-slim), or to a digest (python:3.13-slim@sha256:...) for byte-for-byte repeatability. Use a bot like Dependabot or Renovate to bump it, so you still get security patches. - Install from lockfiles:
uv sync --locked,npm ci. - Scan images for known vulnerabilities (CVEs) in CI and fail the build on critical ones.
docker scout cves myapi:1.0 # Docker Scout, built into the CLItrivy image --severity HIGH,CRITICAL myapi:1.0 # Trivy, open sourceMatch each practice to the risk it reduces.
Healthchecks, logs, and limits
A healthcheck lets Docker (and Compose, and some platforms) know whether the app inside is actually working, not just running. Slim images often lack curl, so use the language you already have:
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"]Kubernetes and ECS use their own health probes configured outside the image, so treat the Dockerfile HEALTHCHECK as useful for Docker and Compose, not universal.
Log to stdout and stderr, not to files. The container runtime collects those streams, docker logs shows them, and production platforms ship them to CloudWatch, Datadog, or Loki. Log files inside the container fill the writable layer and vanish with it. Set PYTHONUNBUFFERED=1 so Python does not hold logs in a buffer.
Set resource limits so one leaky container cannot starve the rest of the machine:
docker run --memory 512m --cpus 1.0 myapi:1.0services:
api:
deploy:
resources:
limits:
memory: 512M
cpus: "1.0"Graceful shutdown and PID 1
During every deploy, the platform stops old containers. docker stop sends SIGTERM to the process with PID 1, waits (10 seconds by default; Kubernetes waits 30), then sends SIGKILL, which cannot be caught. A well-behaved app uses that window to finish in-flight requests and close database connections.
POST /orders (in flight)
Two common ways to break this:
- Shell form CMD.
CMD uvicorn app.main:appruns/bin/sh -c ..., soshis PID 1 and does not forward SIGTERM. The app is killed hard after 10 seconds. Use exec form. - Entrypoint scripts without
exec. If a script runs migrations and then starts the app, it mustexecthe app so the app replaces the shell as PID 1.
#!/bin/shset -ealembic upgrade headexec "$@"PID 1 is also special in Linux: it gets no default signal handlers and must reap zombie child processes. If your app spawns subprocesses and does neither, run it with docker run --init (or init: true in Compose), which puts a tiny init process (tini) in front.
Run this model of a deploy stopping containers with a 10 second grace period.
Press Run (⌘ Enter) to see what happens.CMD python -m app. What is the most likely fix?Tag with the git SHA and push from CI
Production should never run latest. Tag every image with the git commit SHA it was built from. Then any running container tells you exactly which code it has, rollbacks mean redeploying an older tag, and two deploys can never silently differ. Add semantic version tags for releases.
Press Run (⌘ Enter) to see what happens.In GitHub Actions, the official Docker actions do this for you: log in, compute tags, build with a layer cache, and push.
name: docker
on:
push:
branches: [main]
tags: ["v*"]
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=sha
type=semver,pattern={{version}}
type=ref,event=branch
- uses: docker/build-push-action@v6
with:
context: ./backend
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=maxGITHUB_TOKEN is provided by Actions, so no long-lived password is stored. cache-from and cache-to keep layers between runs, so CI builds get the same caching benefits as your laptop. Add a Trivy or Docker Scout step before the push to fail on critical CVEs.
Order the steps of a CI pipeline that ships an image.
- Tap the steps below in the right order.
- distroless
- Base images with only the language runtime and its libraries: no shell, no package manager.
- build secret
- A secret mounted into one
RUNstep with--mount=type=secret, never stored in a layer. - SIGTERM
- The polite stop signal sent by
docker stop. The app should finish work and exit. - PID 1
- The container's main process. It must receive signals (exec form) or the container cannot stop gracefully.
- CVE
- A publicly catalogued security vulnerability. Scanners match image packages against CVE databases.
- immutable tag
- A tag like the git SHA that is never moved, so it always names the same image.