Docker Container Builder
Generates production-ready, optimized Dockerfiles with multi-stage builds, caching, and tagging for any application.
Example run
Generated by Claude Opus 5.5 on November 25, 2026
Inputs used
- Application name
- invoicely-api
- Language and version
- Python 3.12
- Build tool
- pip with requirements.txt (compiled via pip-tools from requirements.in)
- Exposed port
- 8080
- Special requirements
- invoicely-api is a FastAPI service (served via uvicorn with 4 workers) that talks to PostgreSQL 15 and Redis 7. Build-time needs gcc and libpq-dev to compile psycopg2 and cryptography wheels; the runtime image only needs the shared libpq.so.5, not the full -dev package. Required environment variables at runtime: DATABASE_URL, REDIS_URL, JWT_SECRET_KEY, SENTRY_DSN, and LOG_LEVEL (default "info"). JWT_SECRET_KEY and DATABASE_URL must never be baked into the image or committed to a layer — they're injected at deploy time via Kubernetes secrets mounted as env vars, so the Dockerfile must not COPY any .env file. The app reads Alembic migrations from /app/migrations and expects them present in the final image (read-only). It needs tzdata installed because invoices are timestamped in the customer's local timezone (Europe/Warsaw, America/New_York, Asia/Tokyo are the three currently supported). A GET /healthz endpoint returns 200 once the DB connection pool is warm, so the container HEALTHCHECK should hit that. The process must run as a non-root user (uid 1000, named "appuser") since our cluster's PodSecurityPolicy rejects root containers. Final image should stay under 180 MB if possible.
- Registry / tag convention
- ghcr.io/example-org/invoicely-api, tagged as :1.4.0 for the semver release and also updating :latest on main-branch builds
invoicely-api: Production Docker Setup
Assumptions
None of these blocked the build, but please confirm them. Each one maps to a single line you can change.
| # | Assumption | Where it shows up |
|---|---|---|
| A1 | The ASGI app object is at app/main.py → app. The package dir is app/, with migrations/ and alembic.ini at the repo root. |
COPY lines and CMD |
| A2 | requirements.txt was compiled with pip-compile --generate-hashes, so every pin has a hash. |
--require-hashes |
| A3 | You depend on psycopg2, not psycopg2-binary. The -binary variant bundles its own libpq, which makes the gcc/libpq-dev builder pointless. |
builder stage |
| A4 | cryptography installs from its manylinux wheel. If you force a source build (--no-binary), the builder also needs a Rust toolchain. |
builder stage |
| A5 | The container clock runs in UTC (TZ=UTC). The app converts to customer zones itself via zoneinfo. |
ENV TZ |
| A6 | The target is linux/amd64. Add linux/arm64 to --platform if you run ARM nodes. |
build command |
| A7 | The source repo is github.com/example-org/invoicely-api. It's used only for the OCI source label that links the GHCR package to the repo. |
LABEL |
If A2 is wrong, remove --require-hashes. Better, regenerate with pip-compile --generate-hashes requirements.in, because hash-pinned installs are a large part of the reproducibility story.
Base image choices
| Stage | Image | Why |
|---|---|---|
| builder | python:3.12.12-slim-trixie |
Same ABI and glibc as runtime, so compiled wheels (psycopg2) are guaranteed compatible. Debian 13 is the current stable. |
| runtime | python:3.12.12-slim-trixie |
Official, patched CPython 3.12. Distroless only ships Debian's system Python (not 3.12), and Alpine's musl breaks manylinux wheels and slows builds. |
Pin by digest in CI for byte-for-byte reproducibility. Get the digest with docker buildx imagetools inspect python:3.12.12-slim-trixie and use python:3.12.12-slim-trixie@sha256:<digest>. Let Renovate/Dependabot bump it. Bump the patch version too if a newer 3.12.x security release exists.
1. Dockerfile
Rationale: The build has two stages. The builder compiles dependencies into a self-contained virtualenv at /opt/venv using gcc and libpq-dev. The runtime stage copies only that venv plus libpq5 and tzdata, so no compilers or headers ship. Dependency installation is keyed only on requirements.txt, so source edits rebuild in seconds. The process runs as numeric UID 1000 with root-owned, read-only app files and no secrets in any layer.
# syntax=docker/dockerfile:1
# ^ Enables BuildKit features used below (cache/bind mounts).
# Single source of truth for the base image. In CI, override with a digest-pinned ref:
# --build-arg PYTHON_IMAGE=python:3.12.12-slim-trixie@sha256:<digest>
ARG PYTHON_IMAGE=python:3.12.12-slim-trixie
###############################################################################
# Stage 1: builder — compiles wheels (psycopg2) into an isolated virtualenv
###############################################################################
FROM ${PYTHON_IMAGE} AS builder
# gcc + libc6-dev: C toolchain (libc6-dev is only a "Recommends" of gcc, so it must be explicit).
# libpq-dev: headers + pg_config needed to build psycopg2 from source.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
gcc \
libc6-dev \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
# Venv WITHOUT its own copy of pip/setuptools (~15 MB saved in the final image).
# The base image's pip installs into it via `pip --python` (pip >= 22.3).
RUN python -m venv --without-pip /opt/venv
# Only requirements.txt influences this layer's cache key, so code changes never
# trigger a dependency reinstall.
# - bind mount: the manifest is read at build time but never persisted in a layer
# - cache mount: pip's download/wheel cache survives across builds, not in the image
# - --require-hashes: refuse anything whose hash doesn't match the lockfile (supply-chain + reproducibility)
# - --no-deps: the pip-compile'd file is already the full transitive closure; nothing unpinned can sneak in
RUN --mount=type=bind,source=requirements.txt,target=/tmp/requirements.txt \
--mount=type=cache,target=/root/.cache/pip \
pip --python /opt/venv/bin/python install \
--require-hashes \
--no-deps \
-r /tmp/requirements.txt
# Strip debug symbols from compiled extensions (strip comes from binutils, pulled in by gcc).
# Typically saves a few MB, mostly from locally built psycopg2 and any unstripped wheels.
RUN find /opt/venv -type f -name '*.so*' -exec strip --strip-unneeded {} +
###############################################################################
# Stage 2: runtime — only what's needed to run uvicorn
###############################################################################
FROM ${PYTHON_IMAGE} AS runtime
# libpq5: the shared libpq.so.5 that psycopg2 links against (no -dev package).
# tzdata: IANA zone database for zoneinfo (Europe/Warsaw, America/New_York, Asia/Tokyo).
# The user is created in the same layer to avoid an extra layer.
# Numeric UID/GID 1000 so Kubernetes `runAsNonRoot` can verify it.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
libpq5 \
tzdata \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --gid 1000 appuser \
&& useradd --uid 1000 --gid 1000 \
--no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin \
appuser
# Non-secret defaults only. DATABASE_URL, REDIS_URL, JWT_SECRET_KEY and SENTRY_DSN
# are deliberately NOT declared here. They're injected at deploy time from
# Kubernetes Secrets, so they never land in image metadata or `docker history`.
ENV PATH="/opt/venv/bin:${PATH}" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
TZ=UTC \
LOG_LEVEL=info
# Venv from the builder: root-owned, so appuser can execute but not modify it.
COPY --from=builder /opt/venv /opt/venv
WORKDIR /app
# Explicit, least-churn-first COPYs (no `COPY . .`, so nothing unexpected gets in).
# Files stay owned by root, so they're read-only for appuser (satisfies "migrations read-only").
COPY alembic.ini ./
COPY migrations/ ./migrations/
COPY app/ ./app/
# Pre-compile bytecode at build time, because the app dir is not writable at runtime.
# This avoids recompiling in each of the 4 workers on every start, and works with readOnlyRootFilesystem.
RUN python -m compileall -q /app/app
# Version metadata goes LAST: a changing ARG invalidates every RUN after it,
# so declaring it late keeps the apt/venv layers cached across releases.
ARG VERSION=0.0.0-dev
LABEL org.opencontainers.image.title="invoicely-api" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.source="https://github.com/example-org/invoicely-api" \
org.opencontainers.image.base.name="python:3.12.12-slim-trixie"
# Numeric form (not "appuser") so kubelet can validate non-root without reading /etc/passwd.
USER 1000:1000
EXPOSE 8080
# Uses Python's stdlib instead of installing curl (saves ~5 MB and avoids extra CVE surface).
# urlopen raises on any non-2xx status, giving a non-zero exit code.
# start-period gives the DB pool time to warm before failures count.
HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=4)"]
# This is CMD rather than ENTRYPOINT so a Kubernetes Job can reuse the image with
# `alembic upgrade head`. `sh -c` is needed only to expand $LOG_LEVEL at runtime;
# `exec` replaces the shell so uvicorn is PID 1 and receives SIGTERM directly for graceful shutdown.
CMD ["/bin/sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8080 --workers 4 --log-level \"$LOG_LEVEL\" --no-server-header"]
2. .dockerignore
Rationale: This uses an allowlist: ignore everything, then re-include only the four paths the Dockerfile copies. A stray .env, .git directory, local venv, or credentials file can't reach the build context, even if someone later adds COPY . .. A shrunken context also speeds up uploads to the builder.
# Deny everything by default
*
# Allow only what the Dockerfile actually needs
!requirements.txt
!alembic.ini
!app/
!migrations/
# Re-exclude junk that may live inside allowed directories
**/__pycache__
**/*.py[cod]
**/.pytest_cache
**/.mypy_cache
**/.ruff_cache
**/*.egg-info
# Secrets / local config. Belt-and-braces, never allowed even if nested.
**/.env
**/.env.*
**/*.pem
**/*.key
**/secrets*
3. Build, tag, push and run commands
# Variables
export IMAGE=ghcr.io/example-org/invoicely-api
export VERSION=1.4.0
# Optional but recommended: resolve and pin the base digest
BASE_DIGEST=$(docker buildx imagetools inspect python:3.12.12-slim-trixie \
--format '{{json .Manifest.Digest}}' | tr -d '"')
# Build (BuildKit is required for the cache/bind mounts; it's the default in Docker >= 23)
docker buildx build \
--platform linux/amd64 \
--build-arg PYTHON_IMAGE="python:3.12.12-slim-trixie@${BASE_DIGEST}" \
--build-arg VERSION="${VERSION}" \
--tag "${IMAGE}:${VERSION}" \
--load \
.
# Tag :latest (main-branch builds only)
docker tag "${IMAGE}:${VERSION}" "${IMAGE}:latest"
# Push (GHCR_TOKEN = PAT or GITHUB_TOKEN with write:packages)
echo "${GHCR_TOKEN}" | docker login ghcr.io -u "<github-username>" --password-stdin
docker push "${IMAGE}:${VERSION}"
docker push "${IMAGE}:latest" # main only
In GitHub Actions, gate the :latest step with if: github.ref == 'refs/heads/main'.
Run locally. Secrets come in at runtime only. local.env is outside the image and excluded by .dockerignore.
docker run --rm \
--name invoicely-api \
-p 8080:8080 \
--env-file ./local.env \
--read-only --tmpfs /tmp \
--cap-drop ALL \
--security-opt no-new-privileges \
"${IMAGE}:${VERSION}"
local.env should contain DATABASE_URL, REDIS_URL, JWT_SECRET_KEY, SENTRY_DSN and optionally LOG_LEVEL.
Run migrations with the same image:
docker run --rm --env-file ./local.env "${IMAGE}:${VERSION}" alembic upgrade head
Verify the image:
docker image ls "${IMAGE}:${VERSION}" # size
docker run --rm --entrypoint id "${IMAGE}:${VERSION}" # expect uid=1000(appuser)
docker history --no-trunc "${IMAGE}:${VERSION}" | grep -Ei 'secret|database_url|jwt' \
|| echo "OK: no secrets in layer metadata"
docker run --rm --entrypoint python "${IMAGE}:${VERSION}" \
-c "from zoneinfo import ZoneInfo as Z; [Z(z) for z in ('Europe/Warsaw','America/New_York','Asia/Tokyo')]; print('tz ok')"
4. Expected size and how it was reduced
Estimate: about 160–180 MB uncompressed, about 55–65 MB compressed in GHCR. The exact figure depends on your dependency set.
| Component | Approx. size |
|---|---|
python:3.12-slim-trixie base |
~120 MB |
libpq5 + its shared deps (ldap, sasl, gssapi) and tzdata |
~8–10 MB |
/opt/venv (FastAPI, pydantic-core, uvicorn, SQLAlchemy, psycopg2, cryptography, redis, sentry-sdk, alembic) |
~35–50 MB |
App code, migrations and .pyc |
< 2 MB |
How the size was reduced:
- No gcc, binutils, headers or
libpq-devin the final image. They stay in the builder. - The venv is created
--without-pip, which saves about 15 MB versus a normal venv. - Compiled
.sofiles are stripped. curlis not installed. The healthcheck uses the Python stdlib.--no-install-recommendsis used, and apt lists are removed in the same layer.- The pip cache lives in a BuildKit cache mount, never in a layer.
- The allowlist
.dockerignorekeeps tests, docs and.gitout.
If you land above 180 MB, try these in order:
- Replace
uvicorn[standard]with plainuvicornplus onlyuvloopandhttptools.watchfilesis dev-only. - Audit
sentry-sdkextras. - Add
--no-compileto the pip install. This trades about 10% of venv size for slower cold starts.
Operational notes
-
Kubernetes ignores Docker
HEALTHCHECK. Mirror it as probes:readinessProbe: { httpGet: { path: /healthz, port: 8080 }, periodSeconds: 10 } livenessProbe: { httpGet: { path: /healthz, port: 8080 }, initialDelaySeconds: 40, periodSeconds: 30 }Consider a lighter liveness endpoint that doesn't depend on the DB. Otherwise a Postgres blip restarts every pod.
-
Matching securityContext. The image is built to support this:
securityContext: runAsNonRoot: true runAsUser: 1000 runAsGroup: 1000 readOnlyRootFilesystem: true allowPrivilegeEscalation: false capabilities: { drop: ["ALL"] }Mount an
emptyDirat/tmpbecause uvicorn and multipart uploads may need scratch space. -
LOG_LEVELmust be lowercase (debug/info/warning/error/critical). Uvicorn's CLI is case-sensitive. -
apt versions aren't pinned. Debian removes superseded package versions from mirrors, so pinned versions eventually break builds. Reproducibility comes from the base image digest instead. If you need fully frozen apt state, point apt at
snapshot.debian.org. -
File permissions come from the build context. If CI checks out files as
0600(unusual), appuser can't read them. Standard git checkouts produce0644, which works as-is.
Related prompts
DevOps Automation Specialist
Acts as a DevOps engineer to design, optimize, and troubleshoot CI/CD pipelines, infrastructure as code, and cloud automation.
Cybersecurity Audit Specialist
Run a structured cybersecurity audit of an organization, prioritizing risks and producing an actionable remediation roadmap.
Ansible Automation Playbook Creator
Generates production-ready, idempotent Ansible playbooks and roles for any infrastructure automation or configuration task.
Kubernetes Resource Diagnostics
Diagnoses a failing Kubernetes resource and returns root cause plus a step-by-step fix.