Skip to content

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.

17 min read0/5 questions

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.

BaseSize (about)What is insideTradeoffs
python:3.131 GBFull Debian, compilers, git, curlEasy to build in; far too much to ship
python:3.13-slim120 MBMinimal Debian + PythonThe sensible default. glibc, so wheels just work
python:3.13-alpine50 MBAlpine Linux + PythonTiny, but uses musl libc: some packages compile from source, and builds can get slower and bigger
Distroless (gcr.io/distroless/...)50 to 70 MBOnly the runtime and its libraries, no shell, no package managerVery small attack surface; harder to debug
scratch0 MBNothing at allOnly 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.

Attack surface by base image
  1. your app
  2. language runtime (Python / Node)
  3. shell, coreutilsslim and alpine have these
  4. package manager (apt / apk)slim and alpine have these
  5. compilers, git, curl, docsonly the full image

python:3.13: everything. Hundreds of packages, so scanners report many CVEs, most in tools you never call.

1/3

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.

Quick check
A Dockerfile does COPY .npmrc . (it contains a private registry token), then RUN npm ci, then RUN rm .npmrc. Is the token in the pushed image?
Need a nudge? A hint rules out a wrong answer.

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 ci
docker 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 source
Match the pairs0/5 matched

Match each practice to the risk it reduces.

Choose an item, then its match on the other side.

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.0
compose.yaml
services:
  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.

docker stop, done right
DockerApp (PID 1)ClientPOST /orders (in flight)SIGTERM201 Createdexit 0

POST /orders (in flight)

1/4

Two common ways to break this:

  • Shell form CMD. CMD uvicorn app.main:app runs /bin/sh -c ..., so sh is 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 must exec the app so the app replaces the shell as PID 1.
docker-entrypoint.sh
#!/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.

Pythonshutdown.py
def stop(name: str, pid1_gets_sigterm: bool, request_ms: int, grace_s: int = 10) -> None: if not pid1_gets_sigterm: print(f"{name}: SIGTERM ignored, waited {grace_s}s, SIGKILL -> exit 137, request dropped") elif request_ms / 1000 <= grace_s: print(f"{name}: finished request in {request_ms} ms -> exit 0") else: print(f"{name}: still busy after {grace_s}s, SIGKILL -> exit 137") stop("exec form", pid1_gets_sigterm=True, request_ms=800)stop("shell form", pid1_gets_sigterm=False, request_ms=800)stop("slow job", pid1_gets_sigterm=True, request_ms=45_000)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Every deploy takes 10 extra seconds per container and the logs show exit code 137. The Dockerfile ends with CMD python -m app. What is the most likely fix?
Need a nudge? A hint rules out a wrong answer.

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.

Pythontags.py
def tags_for(ref: str, sha: str) -> list[str]: tags = [f"sha-{sha[:7]}"] if ref.startswith("refs/tags/v"): major, minor, patch = ref.removeprefix("refs/tags/v").split(".") tags += [f"{major}.{minor}.{patch}", f"{major}.{minor}", major] elif ref == "refs/heads/main": tags.append("main") return tags print(tags_for("refs/heads/main", "7f3c2a1e9b"))print(tags_for("refs/tags/v1.4.2", "c0ffee12ab"))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

def tags_for(ref, sha):
  tags = [f"sha-{sha[:7]}"]
  if ref.startswith("refs/tags/v"):
      major, minor, patch = ref.removeprefix("refs/tags/v").split(".")
      tags += [f"{major}.{minor}", major]
  return tags

print(tags_for("refs/tags/v2.0.5", "abcdef123456"))
Need a nudge? Hints walk you through it.

In GitHub Actions, the official Docker actions do this for you: log in, compute tags, build with a layer cache, and push.

.github/workflows/docker.yml
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=max

GITHUB_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.

Put it in order6 steps

Order the steps of a CI pipeline that ships an image.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
distroless
Base images with only the language runtime and its libraries: no shell, no package manager.
build secret
A secret mounted into one RUN step 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.