Dockerfile Patterns for Python APIs
Practical Dockerfile patterns for FastAPI and Python services.
- Status
- evergreen
- Visibility
- public
- 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
latesttags 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
Docker Production Checklist
A checklist for production-friendly Docker images and container runtime behavior.
FastAPI Production Checklist
A compact checklist for taking a FastAPI service from useful prototype to production-ready backend.
GCP Cloud Run Checklist
A deployment checklist for containerized backend services on Google Cloud Run.
Cloudflare Pages Deployment Runbook
A deployment checklist for publishing the knowledge base to Cloudflare Pages and mapping notes.bianrui.net.
Secrets Management Checklist
A checklist for safely handling API keys, database credentials, and service secrets.
Backlinks
Docker Production Checklist
A checklist for production-friendly Docker images and container runtime behavior.
GCP for Backend Engineers
A backend-focused map of Google Cloud services for APIs, data, jobs, secrets, and observability.
Kubernetes Basics for AI Workloads
A practical map of Kubernetes concepts that matter for backend and AI infrastructure work.