Skip to content

Dockerfile best practices for production images

How to write a Dockerfile that builds reproducibly, caches well, ships small, runs non-root, and survives upstream changes. The practices that separate prototype images from production ones.

A Dockerfile that builds on a laptop is not the same artifact as one that builds in CI, ships to a registry, and runs as a non-root process in a hardened orchestrator. The differences are small textually but large operationally. This article catalogues the practices we apply to every Dockerfile we ship — what to do, what to avoid, and why each line of a production Dockerfile is the way it is.

How to verify

Audit an existing Dockerfile and the image it produces:

# Image size and layer breakdown
docker image inspect <image> --format '{{.Size}} {{.Architecture}}'
docker history <image> --no-trunc --format "table {{.CreatedBy}}\t{{.Size}}"

# User and capabilities at runtime
docker run --rm <image> id
docker run --rm <image> cat /etc/os-release

# Static analysis
docker run --rm -i hadolint/hadolint < Dockerfile

# Vulnerability scan (also see docker-image-security-scanning article)
trivy image <image>

If id reports uid=0(root), the image runs as root. If docker history shows a single 1.2 GB layer, the build is not layered for cache. Both are signals the Dockerfile needs work.

What’s happening

A Dockerfile is a sequence of layered filesystem operations. Each instruction (RUN, COPY, ADD) creates a new layer; layers are cached individually and reused across builds whenever their inputs match. Two consequences follow:

First, layer order matters for cache hit rate. Stable inputs (base image, system packages) belong at the top; volatile inputs (your application code) belong at the bottom. A change to app.py should not invalidate the apt-get layer.

Second, layers persist what they contain even when later removed. Doing RUN apt-get install foo && rm /var/cache/apt/... in two separate RUN instructions creates two layers — the first still contains the apt cache. The cleanup must happen in the same layer as the install.

The procedure

  1. Pin a specific base image, not a moving tag:
# Bad: tag floats, build is not reproducible
FROM python:3.12

# Good: pinned by digest, exact bits every build
FROM python:3.12.4-slim-bookworm@sha256:abc123...
  1. Combine related RUN statements; clean up in the same layer:
RUN apt-get update \
 && apt-get install -y --no-install-recommends \
      ca-certificates curl gnupg \
 && rm -rf /var/lib/apt/lists/*

--no-install-recommends skips suggested packages, often saving 50-200 MB. The rm -rf /var/lib/apt/lists/* removes the package index in the same layer.

  1. Order instructions from least-volatile to most-volatile so cache hits compound:
FROM python:3.12.4-slim-bookworm AS runtime
WORKDIR /app

# System packages — changes rarely
RUN apt-get update && apt-get install -y --no-install-recommends libpq5 \
 && rm -rf /var/lib/apt/lists/*

# Dependencies — changes when requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Application code — changes every build
COPY src/ ./src/

requirements.txt copied alone before src/ means edits to application code don’t invalidate the pip install layer — the most expensive step.

  1. Use a .dockerignore file aggressively. Without it, the entire build context (often the whole repo) is sent to the daemon, slowing builds and exposing secrets:
.git
.github
node_modules
__pycache__
*.pyc
.env*
.vscode
.idea
Dockerfile
.dockerignore
README.md
  1. Run as a non-root user. Most base images do not do this for you:
RUN groupadd --system --gid 1000 app \
 && useradd --system --uid 1000 --gid app --no-create-home --shell /sbin/nologin app

COPY --chown=app:app src/ ./src/
USER 1000:1000

The numeric UID/GID form (USER 1000:1000) is more portable than the name form — Kubernetes’ runAsNonRoot: true admission check requires a numeric UID.

  1. Use multi-stage builds to leave build tools out of the runtime image. See multi-stage builds for the full pattern.

  2. Set a sensible WORKDIR, never use cd:

WORKDIR /app
# Subsequent RUN/COPY/CMD all relative to /app
  1. Prefer COPY over ADD. ADD has surprising behavior (URL fetching, tar extraction). If you need those, do them explicitly.

  2. Declare ports with EXPOSE and the entrypoint with ENTRYPOINT/CMD. ENTRYPOINT should be the binary; CMD should be the default arguments:

EXPOSE 8080
ENTRYPOINT ["/usr/bin/dumb-init", "--", "python", "-m", "uvicorn"]
CMD ["app.main:app", "--host", "0.0.0.0", "--port", "8080"]

dumb-init (or tini) reaps zombie processes and forwards signals; Python (and Node, and many others) running as PID 1 will ignore SIGTERM without this.

  1. Add a HEALTHCHECK so the orchestrator has a signal beyond “process alive”:
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD curl -fsS http://localhost:8080/healthz || exit 1
  1. Label the image with provenance:
ARG GIT_SHA
ARG BUILD_DATE
LABEL org.opencontainers.image.source="https://github.com/example/web" \
      org.opencontainers.image.revision="${GIT_SHA}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.licenses="MIT"

Provenance labels make docker inspect answer “where did this image come from?” without checking the registry.

Common pitfalls

  • Using latest (or any floating tag) as a base — your build is not reproducible and a transitive upgrade can break production silently.
  • Copying secrets in (COPY .env .) — they persist in the image layer even if a later step deletes the file. Use build secrets via BuildKit (--mount=type=secret) instead.
  • Forgetting --no-install-recommends on apt-get install, doubling image size for no functional gain.
  • Setting USER early and then trying to RUN apt-get install — apt needs root. Switch to the unprivileged user only after the last root operation.
  • Using chmod -R 777 to “fix permissions” — set ownership explicitly with COPY --chown= and grant the minimum permissions the process needs.

We treat every client Dockerfile as a production artifact that ships through our build and release pipeline. The patterns above are codified in our base templates so the operating model — including managed operations for the running containers — starts from the same place.