A complete guide to writing production-grade Docker containers that are lightweight, secure, and build fast

Share
Photo by Milad Fakurian on Unsplash

Disclaimer: This article is not about the basics of Docker/containers. It’s about building production-grade containers. You can learn about Docker fundamentals in this blog I wrote last year.

In this blog, you will learn how to build production-grade containers that are lightweight, build fast, and are secure to run.

The container journey starts when you get tired of the phrase “It works on my machine” and want to package the application in a way that works on everyone’s machine and can handle millions of user requests.

Some did it out of necessity; others did it to follow the trend.

The first container

Building containers starts with a basic Dockerfile with some simple instructions (Base image, copy code, install deps and run it)

FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD python app.py

It is good enough to build and run containers

Then you check the image size, which goes well over 1GB.

Your app is 20MB of code. The other 1GB is a full Debian OS with compilers, man pages, and hundreds of packages you will never use.

Every deploy pulls 1GB. Every node stores it. Every CVE in those packages is now your problem.

That means we should make it lighter to start with

So you use a slim base image.

FROM python:3.12-slim

python:3.12-slim drops that to around 150MB. Same Python. Same Debian. Just without everything you never needed.

You might think Alpine is even smaller. It is. But Alpine uses musl instead of glibc, so many Python wheels don’t work and end up being compiled from source.

Your builds get slower, and you hit strange runtime bugs. For most apps, slim is the right starting point.

But now your builds are painfully slow.

You change one line of code. Docker rebuilds everything. Reinstalls every dependency. 6 minutes, every time.

Why? Because you copied all your code before installing dependencies. Docker caches layers in order. When a layer changes, every layer after it gets rebuilt too. Your code changes all the time, so the pip install layer after it never gets cached.

Your cache is useless when the most-changed thing comes first.

So you order your layers correctly. Copy requirements.txt first. Install dependencies. Then copy your code.

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD python app.py

Dependencies rarely change. Code changes constantly.

Now, a code change only rebuilds the last layer. The install is cached. 6 minutes becomes 20 seconds.

Bad layer ordering broke your cache. Putting what rarely changes first fixed that.

But COPY . . is copying more than you think. Your .git folder. Your local venv. node_modules. Test data. Your .env file with real credentials.

All of it goes into the build context. Some of it ends up in the image. Your image is bigger than it needs to be. Your cache breaks every time any file in the repo changes.

Worse, your .env file is now baked into an image sitting in a registry. That’s not a big image. That’s a leaked secret.

So you use a .dockerignore. It works like .gitignore, but for your build context. Exclude .git, .env, venvs, tests, local artifacts.

.git
.env
venv/
node_modules/
__pycache__/
tests/
*.log

Smaller context. Faster builds. Better caching. No secrets copied in by accident.

COPY . . was copying everything in the repo. .dockerignore fixed that.

Now you need system packages. And your image grows again. Your app needs gcc and libpq-dev to compile psycopg2. You add a RUN apt-get install line. Then a separate RUN line to clean up.

RUN apt-get update && apt-get install -y gcc libpq-dev
RUN rm -rf /var/lib/apt/lists/*

The image doesn’t shrink at all.

Every RUN instruction creates a layer. Deleting files in a later layer doesn’t remove them from the earlier one. They’re still there, just hidden. Same with pip. It keeps a download cache you’ll never use at runtime.

So you clean up in the same layer. apt-get update, install, and rm -rf /var/lib/apt/lists/* in a single RUN. pip install — no-cache-dir. Install with — no-install-recommends so apt doesn’t pull in extras.

RUN apt-get update \
&& apt-get install -y --no-install-recommends gcc libpq-dev \
&& rm -rf /var/lib/apt/lists/*

What is created and deleted in the same layer never appears in the image.

Cleanup in separate layers didn’t save anything. Doing it in the same layer fixed that.

But your production image still ships a compiler. gcc is needed to build your dependencies. It’s not needed to run them. Yet it sits in your production image. Along with build headers and dev libraries. More size. More CVEs. More tools for an attacker to use if they get in.

Your build environment and your runtime are not the same thing.

So you use multi-stage builds. Stage one is the builder.

It has compilers and build tools. It installs dependencies into a virtual environment.

Stage two is the runtime. A clean slim image. You copy only the virtual environment and your code from the builder.

# Stage 1: build
FROM python:3.12-slim AS builder
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends gcc libpq-dev \
&& rm -rf /var/lib/apt/lists/*
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt


# Stage 2: run
FROM python:3.12-slim
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq5 \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY . .
CMD python app.py

The compiler junk never reaches production. The final image contains only what’s needed to run, plus libpq5, the small runtime library that psycopg2 actually needs.

For compiled languages like Go, you can go further. Build a static binary and ship it on distroless or even scratch. A 10MB image with no shell and no package manager.

Let’s fix the security now

Docker runs containers as root by default. Your app has a vulnerability. An attacker gets code execution inside the container. They’re root. They can modify files, install tools, and if there’s a container escape bug or a misconfigured mount, root in the container gets much closer to root on the node.

Your app never needed root; any user can run it as a non-root user.

During the image build, you create a user in the Dockerfile. Switch to it with USER before CMD (Make sure your app files are owned by that user)

RUN useradd --create-home --uid 10001 appuser
COPY --chown=appuser:appuser . .
USER appuser

In Kubernetes, enforce it with runAsNonRoot in the securityContext, so a root image can’t be deployed by mistake.

securityContext:
runAsNonRoot: true
runAsUser: 10001

A compromised app now has the permissions of a regular user, not root.

Then you need a secret during the build. Your app depends on a private package. Pip needs a token to pull it. So you pass it in with ARG or ENV.

ARG PIP_TOKEN
RUN pip install --extra-index-url https://__token__:${PIP_TOKEN}@pypi.example.com/simple -r requirements.txt

The build works. You push the image.

Anyone who pulls it can run docker history and read your token. ARG values used in RUN commands get recorded in the image history. ENV values get baked into the image config.

Your private registry token is now public to anyone with pull access.

So you use BuildKit secret mounts. RUN — mount=type=secret,id=pip_token mounts the secret only for that one command.

RUN --mount=type=secret,id=pip_token \
PIP_EXTRA_INDEX_URL="https://__token__:$(cat /run/secrets/pip_token)@pypi.example.com/simple" \
pip install --no-cache-dir -r requirements.txt
docker build --secret id=pip_token,env=PIP_TOKEN -t myapp .

Now your secrets aren’t written to any layer, aren’t stored in history, and aren’t in the final image. The build gets the secret, but the final image doesn’t.

Your image looks fine today. Next month, it breaks.

Now there is the floating tag problem

FROM python:3.12-slim pulls whatever is tagged today. Next month, the tag points to a new image. A new patch version, updated system libraries. Your Dockerfile didn’t change. Your image did. Something breaks in production, and you can’t reproduce last month’s build.

A floating tag is a dependency you never agreed to update.

So you pin your base image. Pin to a specific version like python:3.12.7-slim-bookworm. For full reproducibility, pin to the digest.

FROM python:3.12.7-slim-bookworm
# or, fully reproducible
FROM python:3.12.7-slim-bookworm@sha256:<digest>

Use Renovate or Dependabot to open PRs when a new version comes out. You get updates on purpose, not by accident.

But pinned images get old. And old images collect vulnerabilities. The base image you pinned 6 months ago now has 40 known CVEs. Nobody noticed. Nothing in your pipeline checks. You find out when a security audit flags it. Or worse, when someone exploits it.

What you don’t scan, you don’t know about.

So you scan your images. Trivy, Grype, or your registry’s built-in scanning (ECR, Artifact Registry, Harbor). Run the scan in CI on every build. Fail the pipeline on critical and high CVEs that have a fix.

trivy image --severity CRITICAL,HIGH --ignore-unfixed --exit-code 1 myregistry/myapp:1.4.2

Every image is checked before it reaches a cluster.

Vulnerabilities went unnoticed until audits. Image scanning in CI fixed that.

Make it fast in CI and safe to stop

Locally, your builds are fast. In CI, they’re slow again.

Every CI run starts on a fresh runner with an empty Docker cache. Your carefully ordered layers mean nothing. Every build reinstalls everything from scratch. And even with a warm cache, changing a single line in requirements.txt re-downloads every package.

A cache that disappears after every run isn’t a cache.

So you use cache mounts and a remote cache. RUN — mount=type=cache,target=/root/.cache/pip keeps pip’s download cache between builds, without putting it in the image. Changing one dependency now downloads one package.

RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt

Drop — no-cache-dir here, because the cache now lives outside the image and you want pip to use it.

For CI, use — cache-to and — cache-from with a registry or the GitHub Actions cache backend. Fresh runners pull cached layers instead of rebuilding them.

docker buildx build \
--cache-from type=registry,ref=myregistry/myapp:buildcache \
--cache-to type=registry,ref=myregistry/myapp:buildcache,mode=max \
-t myregistry/myapp:1.4.2 \
--push .

CI builds go from 8 minutes back to under 1.

Fresh CI runners threw away your cache. Cache mounts and remote caching fixed that.

Your image is slim, secure, and fast. Then Kubernetes tries to stop it.

A rolling update starts. Kubernetes sends SIGTERM to your container. Your app ignores it. 30 seconds later, Kubernetes sends SIGKILL. Your app dies mid-request. In-flight requests fail. Database connections are left hanging.

The reason is one line:

CMD python app.py

That’s shell form. Your app runs as a child of /bin/sh, and sh is PID 1. The shell doesn’t forward signals to your app. Your app never knew it was asked to stop.

So you use exec form and handle signals properly. CMD [“python”, “app.py”] runs your app directly as PID 1. It receives SIGTERM.

CMD ["python", "app.py"]

Make your app handle SIGTERM: stop accepting new requests, finish the current ones, close connections, exit.

import signal
import sys
def shutdown(signum, frame):
# stop accepting requests, finish in-flight work, close connections
sys.exit(0)
signal.signal(signal.SIGTERM, shutdown)

If your app spawns child processes, add tini as an init process to forward signals and clean up zombie processes. Rolling updates become boring. That’s the goal.

Shell form swallowed shutdown signals. Exec form and proper signal handling fixed that.

The full story

Here is everything in one Dockerfile:

# syntax=docker/dockerfile:1
FROM python:3.12.7-slim-bookworm AS builder
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends gcc libpq-dev \
&& rm -rf /var/lib/apt/lists/*
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=secret,id=pip_token \
PIP_EXTRA_INDEX_URL="https://__token__:$(cat /run/secrets/pip_token)@pypi.example.com/simple" \
pip install -r requirements.txt

FROM python:3.12.7-slim-bookworm
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq5 tini \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --create-home --uid 10001 appuser
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY --chown=appuser:appuser . .
USER appuser
ENTRYPOINT ["tini", "--"]
CMD ["python", "app.py"]

To summarize the full story:

  • The full base image shipped an OS you didn’t need. Slim images fixed that.
  • Bad layer ordering broke your cache. Correct layer ordering fixed that.
  • COPY . . copied everything, secrets included. .dockerignore fixed that.
  • Cleanup in separate layers saved nothing. Same-layer cleanup fixed that.
  • Build tools leaked into production. Multi-stage builds fixed that.
  • Running as root made every bug a bigger breach. A non-root user fixed that.
  • ARG and ENV leaked build secrets. Secret mounts fixed that.
  • Floating tags made builds unpredictable. Pinning fixed that.
  • Vulnerabilities went unnoticed. Image scanning fixed that.
  • Fresh CI runners lost your cache. Cache mounts and remote caching fixed that.
  • Shell form swallowed shutdown signals. Exec form fixed that.

Production-ready containers aren’t built on day one. They get there through a series of hard lessons.

Share
Akhilesh Mishra

Akhilesh Mishra

I am Akhilesh Mishra, a self-taught Devops engineer with 11+ years working on private and public cloud (GCP & AWS)technologies.

I also mentor DevOps aspirants in their journey to devops by providing guided learning and Mentorship.

Topmate: https://topmate.io/akhilesh_mishra/