docs Jun 28, 2026 updated Jun 28, 2026

Dockerfile Patterns for Python APIs

Practical Dockerfile patterns for FastAPI and Python services.

Status
evergreen
Visibility
public
Role Area
Docker / Kubernetes / CI/CD
Priority
P0
Confidence
developing
Category
Deployment
Difficulty
intermediate
Published
Jun 28, 2026
Updated
Jun 28, 2026

Goals

A production Docker image should be reproducible, small enough to move quickly, and boring to run.

Useful Defaults

  • Pin the Python major/minor version.
  • Install dependencies before copying the full app to improve layer caching.
  • Avoid baking secrets into build args or image layers.
  • Run as a non-root user.
  • Use a clear startup command.

Example Shape

FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

RUN useradd --create-home appuser
USER appuser

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]

Things to Avoid

  • latest tags for production images.
  • Installing compilers in the final runtime image unless needed.
  • Copying .env, local caches, notebooks, or test artifacts.
  • Running database migrations implicitly on every container start.

Production Questions

  • What is the image digest deployed to production?
  • How are vulnerabilities scanned?
  • Where are runtime secrets injected?
  • How does the service shut down during deploys?

Source Links

Related Notes

Cheat Sheets Jun 28, 2026 P0 intermediate

FastAPI Production Checklist

A compact checklist for taking a FastAPI service from useful prototype to production-ready backend.

Cheat Sheets Jun 28, 2026 P0 intermediate

Docker Production Checklist

A checklist for production-friendly Docker images and container runtime behavior.

Cheat Sheets Jun 28, 2026 P0 beginner

GCP Cloud Run Checklist

A deployment checklist for containerized backend services on Google Cloud Run.

Runbooks Jun 28, 2026 P1 beginner

Cloudflare Pages Deployment Runbook

A deployment checklist for publishing the knowledge base to Cloudflare Pages and mapping notes.bianrui.net.

Cheat Sheets Jun 28, 2026 P0 intermediate

Secrets Management Checklist

A checklist for safely handling API keys, database credentials, and service secrets.

Backlinks

Cheat Sheets Jun 28, 2026 P0 intermediate

Docker Production Checklist

A checklist for production-friendly Docker images and container runtime behavior.

Runbooks Jun 28, 2026 P0 intermediate

GCP for Backend Engineers

A backend-focused map of Google Cloud services for APIs, data, jobs, secrets, and observability.