- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Deployment and Monitoring
- Deploy FastAPI with Docker
On this page
How To Deploy FastAPI With Docker
Published on August 17, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Containerising a FastAPI application with Docker produces a self-contained, reproducible artefact that runs identically on any machine — a developer's laptop, a CI server, or a cloud platform. The official FastAPI documentation recommends using fastapi run — which uses Uvicorn internally — as the production CMD. The deprecated tiangolo/uvicorn-gunicorn-fastapi base image should no longer be used. This guide covers writing a correct, production-ready Dockerfile for a FastAPI application, understanding Docker layer caching, handling environment variables and secrets, choosing the right process model, and integrating the container into a Docker Compose stack.
What Docker Does
Docker packages an application and all its dependencies — the Python interpreter, every installed package, and configuration files — into a single image [8†L30-L33]. An image is a static, immutable snapshot [8†L32-L35]. A container is a running instance of that image: an isolated process with its own filesystem, network, and memory space.
The practical consequence: an image built on a MacBook and pushed to a registry runs identically on an Ubuntu server in AWS without any environment setup.
The .dockerignore File
Before writing the Dockerfile, create a .dockerignore file. This tells Docker which files to exclude from the build context — the set of files it can read during docker build. Without it, COPY . . copies everything: .git history, __pycache__, local .env files, test artefacts, and development virtual environments. This bloats the image and risks leaking secrets.
📄 .dockerignore
.git
.gitignore
.env
.env.*
__pycache__
*.pyc
*.pyo
.pytest_cache
.coverage
htmlcov
*.egg-info
dist
build
.venv
venv
node_modules
*.md
tests/
The Dockerfile
The official FastAPI documentation uses fastapi run — which serves the application with Uvicorn — as the CMD [8†L13-L14][1†L7-L10]. Gunicorn is no longer required or recommended for running FastAPI in a container [12†L34-L45][3†L13-L14][3†L24-L27]. Uvicorn's --workers flag provides multi-process support directly, and fastapi run is the idiomatic command for production deployments [1†L26-L29][11†L1-L4].
The
tiangolo/uvicorn-gunicorn-fastapibase image is deprecated and should not be used in new projects [3†L6-L9][12†L39-L41]. Always build from the official Python base image as shown here.
📄 Dockerfile
# Start from the official Python base image — slim variant for smaller size
FROM python:3.13-slim
# Set the working directory inside the container
WORKDIR /code
# Copy only requirements first — this is critical for Docker layer caching
# If requirements.txt hasn't changed, Docker reuses the cached pip install layer
COPY ./requirements.txt /code/requirements.txt
# Install dependencies
# --no-cache-dir: don't store the pip cache inside the image (reduces size)
# --upgrade: ensure the latest compatible versions are installed
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
# Copy application source code
# This comes AFTER pip install so code changes don't invalidate the dependency cache
COPY ./app /code/app
# Run the application using fastapi run (uses Uvicorn internally)
# Exec form is mandatory — shell form breaks graceful shutdown and lifespan events
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
Why exec form for CMD is mandatory
Docker's CMD instruction has two forms:
# Exec form — CORRECT
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
# Shell form — DO NOT USE
CMD fastapi run app/main.py --port 80
The shell form wraps the command in /bin/sh -c, which means the shell process — not fastapi — becomes PID 1 inside the container. When Docker sends a SIGTERM signal to stop the container gracefully, the shell receives it but does not forward it to the child process. The application cannot run its shutdown logic (FastAPI's lifespan cleanup code never executes) and Docker eventually kills it with SIGKILL after a timeout. The exec form makes fastapi PID 1 directly, so it receives and handles the signal correctly.
Why requirements.txt is copied before the source code
Docker builds images layer by layer. Each instruction in the Dockerfile produces a layer. If a layer's inputs have not changed since the last build, Docker uses the cached layer instead of re-executing the instruction — saving significant time.
The pip install step takes the longest — potentially minutes for a large dependency set. By copying requirements.txt before the source code and running pip install immediately after, Docker can cache the entire dependency installation. On subsequent builds triggered by code changes, Docker finds the requirements.txt layer unchanged and skips the pip install entirely. The rebuild completes in seconds rather than minutes.
If COPY . . came first, every code change would invalidate every subsequent layer including pip install.
Project Structure
project/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── db.py
│ ├── models/
│ ├── routers/
│ ├── services/
│ └── core/
├── Dockerfile
├── .dockerignore
├── requirements.txt
└── docker-compose.yml
requirements.txt
Pin versions explicitly to guarantee reproducible builds. An unpinned fastapi will silently upgrade to a new major version on the next docker build, potentially breaking the application.
fastapi[standard] installs FastAPI with uvicorn[standard] and the fastapi CLI — the fastapi run command used in the Dockerfile depends on this extra.
📄 requirements.txt
fastapi[standard]>=0.115.0,<0.116.0
sqlmodel>=0.0.21,<0.0.22
pwdlib[argon2]>=0.2.0,<0.3.0
python-jose[cryptography]>=3.3.0,<4.0.0
python-multipart>=0.0.9,<0.0.10
slowapi>=0.1.9,<0.2.0
psycopg2-binary>=2.9.0,<3.0.0
Environment Variables and Secrets
Never bake secrets into a Docker image. Database passwords, JWT secret keys, and API tokens stored in the image are readable by anyone who can pull it [0†L18]. Use environment variables injected at runtime [5†L36-L38].
📄 app/core/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
database_url: str = "sqlite:///database.db"
jwt_secret_key: str = "change-me-in-production"
jwt_algorithm: str = "HS256"
debug: bool = False
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
settings = Settings()
Install pydantic-settings:
pydantic-settings>=2.0.0,<3.0.0
pydantic-settings reads values from environment variables first, then from a .env file if one is present, then uses the declared defaults. In the container, environment variables are injected via Docker Compose or the orchestration platform — the .env file is excluded from the image by .dockerignore [5†L36-L38].
Building the Image
Build the image from the project root (the directory containing Dockerfile):
docker build -t taskmanager:latest .
Run the container locally for testing:
docker run -d \
--name taskmanager \
-p 8000:80 \
-e DATABASE_URL="sqlite:///database.db" \
-e JWT_SECRET_KEY="local-dev-secret" \
taskmanager:latest
-p 8000:80 maps host port 8000 to container port 80. Visit http://localhost:8000/docs to verify the API is running.
Useful container management commands:
# View running containers
docker ps
# Follow container logs in real time
docker logs -f taskmanager
# Stop the container
docker stop taskmanager
# Remove the container
docker rm taskmanager
# List all local images
docker images
Single Uvicorn Process vs Multiple Workers
The correct process model depends on how you deploy [12†L34-L45].
One process per container (Kubernetes, Docker Swarm)
When using an orchestration platform that manages replication at the cluster level — Kubernetes, Docker Swarm, Nomad — each container should run a single Uvicorn process. The platform spins up multiple identical containers and load-balances between them. Running multiple workers inside each container adds complexity without benefit — the platform is already handling replication.
# Single process — let the cluster handle replication
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
Multiple workers per container (single server, Docker Compose)
When deploying to a single server with Docker Compose — no cluster, no orchestrator — using multiple workers inside a single container is the way to use multiple CPU cores [1†L26-L29][11†L1-L4]:
# Multiple workers — suitable for single-server Docker Compose deployments
CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"]
Set the worker count to the number of CPU cores available on the server. A common rule of thumb is (2 × CPU cores) + 1, but measure performance under load for your specific workload [1†L33-L34].
Behind a reverse proxy
When the container runs behind NGINX, Traefik, or a cloud load balancer, add --proxy-headers so Uvicorn trusts the X-Forwarded-For and X-Forwarded-Proto headers set by the proxy [8†L14-L16]. Without this, request.client.host returns the proxy IP rather than the real client IP, breaking IP-based rate limiting:
CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
Docker Compose: Full Stack
Docker Compose defines and runs multi-container applications from a single configuration file [6†L33-L35]. This stack runs the FastAPI app alongside PostgreSQL, Prometheus, and Grafana — all connected on a shared network.
📄 docker-compose.yml
version: "3.8"
services:
app:
build: .
container_name: taskmanager-app
ports:
- "8000:80"
environment:
- DATABASE_URL=postgresql://taskmanager:secret@db:5432/taskmanager
- JWT_SECRET_KEY=change-this-in-production
- DEBUG=false
depends_on:
db:
condition: service_healthy
restart: unless-stopped
networks:
- taskmanager
db:
image: postgres:16-alpine
container_name: taskmanager-db
environment:
- POSTGRES_USER=taskmanager
- POSTGRES_PASSWORD=secret
- POSTGRES_DB=taskmanager
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U taskmanager"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
networks:
- taskmanager
prometheus:
image: prom/prometheus:latest
container_name: taskmanager-prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
restart: unless-stopped
networks:
- taskmanager
grafana:
image: grafana/grafana:latest
container_name: taskmanager-grafana
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_USER=admin
- GF_SECURITY_ADMIN_PASSWORD=admin
volumes:
- grafana-data:/var/lib/grafana
restart: unless-stopped
networks:
- taskmanager
networks:
taskmanager:
driver: bridge
volumes:
postgres-data:
grafana-data:
depends_on with condition: service_healthy makes the app container wait for PostgreSQL to pass its health check before starting. Without this, FastAPI starts, tries to connect to the database, fails, and crashes before Postgres is ready.
restart: unless-stopped restarts containers automatically after a crash or server reboot — unless explicitly stopped with docker stop.
Start the full stack:
docker-compose up --build -d
Rebuild only the app container after code changes:
docker-compose up --build app -d
Stop everything and remove containers (data volumes are preserved):
docker-compose down
Stop and remove containers and volumes (destroys database data):
docker-compose down -v
Pushing to a Container Registry
Docker Hub is a public registry for container images. Push the image so it can be pulled by a cloud provider or a remote server.
# Log in to Docker Hub
docker login
# Tag the local image with your Docker Hub username
docker tag taskmanager:latest yourusername/taskmanager:latest
# Push the image
docker push yourusername/taskmanager:latest
Pull and run on any machine that has Docker:
docker pull yourusername/taskmanager:latest
docker run -d \
-p 8000:80 \
-e DATABASE_URL="postgresql://..." \
-e JWT_SECRET_KEY="production-secret" \
yourusername/taskmanager:latest
Common Mistakes to Avoid
Using shell form for CMD. Shell form wraps the command in /bin/sh -c, making the shell PID 1. SIGTERM signals are not forwarded to the application, lifespan cleanup never runs, and Docker force-kills the container after a timeout. Always use exec form: CMD ["fastapi", "run", ...].
Not creating a .dockerignore file. Without it, COPY . . copies .git, .env, __pycache__, test files, and the local virtual environment into the image — bloating the image size and potentially leaking secrets.
Baking secrets into the image. Any secret in the Dockerfile or in files copied into the image is visible to anyone who can pull the image. Inject secrets via environment variables at runtime [5†L36-L40].
Copying source code before running pip install. Every code change invalidates the pip install cache layer, forcing a full reinstall on every build. Copy requirements.txt first, run pip install, then copy the source.
Using the deprecated tiangolo/uvicorn-gunicorn-fastapi base image. This image is officially deprecated [3†L40-L41][12†L39-L41]. Build from python:3.13-slim and use fastapi run directly.
Not pinning dependency versions. Unpinned versions in requirements.txt produce different package versions on each build, making builds non-reproducible and making it impossible to determine which dependency version introduced a bug.
Running multiple workers inside containers managed by Kubernetes. The cluster already handles replication across containers. Multiple workers per container adds unnecessary complexity and makes memory limits harder to set accurately. Use one process per container when the cluster manages scaling.
Practice Challenge
- Add a multi-stage Dockerfile that uses a
python:3.13builder stage to compile any C extensions (for packages that need compilation) and copies only the resulting packages into apython:3.13-slimruntime stage, producing a smaller final image with no build tools present [4†L34-L36]. - Add a
healthcheckinstruction to the Dockerfile that callsGET /healthevery 30 seconds:HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost:80/health || exit 1. - Configure a GitHub Actions workflow that builds the Docker image on every push to
main, runspytestinside the container, and pushes the image to a container registry only when all tests pass.
Frequently Asked Questions
What does Docker do when containerizing a FastAPI application?
Docker packages the FastAPI application and all its dependencies—such as the Python interpreter, installed packages, and configuration files—into a single static, immutable image. A container is a running instance of that image, acting as an isolated process with its own filesystem, network, and memory space to ensure identical operation across any machine.
Why is a `.dockerignore` file necessary before building a Docker image?
A `.dockerignore` file prevents unnecessary files—like `.git` history, `__pycache__`, local `.env` files, tests, and virtual environments—from being copied into the build context. This prevents image bloat and avoids risking the leakage of sensitive secrets.
Is Gunicorn still recommended for running FastAPI in a production Docker container?
No, Gunicorn is no longer required or recommended. The official recommendation is to use `fastapi run` (which uses Uvicorn internally) as the `CMD`. Multi‑process support is handled directly via Uvicorn's `--workers` flag, and the official `tiangolo/uvicorn-gunicorn-fastapi` base image has been deprecated.
Why is the exec form mandatory for the `CMD` instruction in the Dockerfile?
The exec form makes `fastapi` run directly as PID 1, allowing it to correctly receive and handle `SIGTERM` signals for graceful shutdowns and execution of lifespan cleanup events. In contrast, the shell form wraps the command in `/bin/sh -c`, preventing the application from intercepting the shutdown signal and forcing Docker to abruptly kill the process with `SIGKILL` after a timeout.
Why should `requirements.txt` be copied into the image before the application source code?
Copying `requirements.txt` first leverages Docker layer caching. Because dependency installation (`pip install`) takes the longest, caching this layer ensures subsequent builds triggered by source code alterations skip the re-installation process entirely, shortening build times from minutes to seconds.
How do I handle environment variables and secrets in a FastAPI Docker container?
Never bake secrets into the image. Use `pydantic-settings` to read configuration from environment variables at runtime. Inject secrets via `-e` flags in `docker run`, through a `.env` file mounted at runtime, or via Docker Compose environment variables. The `.env` file should be excluded from the image using `.dockerignore`.
When should I use a single Uvicorn worker versus multiple workers in the container?
Use a single worker per container when deploying to Kubernetes, Docker Swarm, or any orchestration platform that handles replication at the cluster level. Use multiple workers (`--workers N`) when deploying to a single server with Docker Compose, where there is no external orchestrator to provide horizontal scaling. The worker count is typically set to the number of CPU cores or `(2 × cores) + 1`.
What is the `--proxy-headers` flag and when should I use it?
The `--proxy-headers` flag tells Uvicorn to trust `X-Forwarded-For` and `X-Forwarded-Proto` headers set by a reverse proxy like NGINX or Traefik. Without this flag, `request.client.host` returns the proxy IP rather than the real client IP, breaking IP‑based rate limiting, logging, and security features. Use it when the container runs behind a reverse proxy.
What should I do if my FastAPI container crashes on startup with a database connection error?
The container is likely starting before the database is ready. Use Docker Compose `depends_on` with `condition: service_healthy` to make the app wait for the database health check to pass before starting. Alternatively, implement a retry loop in the application startup code that polls the database until it becomes available.
Why does my container not shut down gracefully when I run `docker stop`?
The `CMD` is likely using shell form instead of exec form. The shell form wraps the command in `/bin/sh -c`, making the shell PID 1, which does not forward `SIGTERM` to the FastAPI application. Use exec form: `CMD ["fastapi", "run", "app/main.py", "--port", "80"]` to ensure the application receives the shutdown signal directly.
What is the difference between `docker-compose down` and `docker-compose down -v`?
`docker-compose down` stops and removes all containers and networks defined in the Compose file, but preserves named volumes so data persists. `docker-compose down -v` stops and removes containers, networks, **and** named volumes, which permanently destroys all persisted data (including database contents). Use `-v` only when you want a completely fresh start.
How do I rebuild only the application container after code changes?
Use `docker-compose up --build app -d`. This rebuilds only the `app` service and restarts it, leaving dependent services like the database and monitoring tools untouched. This is faster than rebuilding the entire stack.
Why are unpinned dependency versions in `requirements.txt` a problem in production?
Unpinned versions (e.g., `fastapi` instead of `fastapi>=0.115.0,<0.116.0`) produce different package versions on each build. A new major release could introduce breaking changes, causing the application to fail in production even though it worked in development. Pinning ensures reproducible builds and makes it possible to trace which version introduced a bug.
Can I use the `tiangolo/uvicorn-gunicorn-fastapi` base image for new projects?
No. This image is officially deprecated and should not be used in new projects. Build your image from `python:3.13-slim` and use `fastapi run` as the `CMD`. The deprecated image relies on Gunicorn, which is no longer recommended for FastAPI deployments.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Deployment and Monitoring
Next
CI/CD and GitHub Actions
-
What Docker Does
-
The
.dockerignoreFile -
The Dockerfile
- Why exec form for
CMDis mandatory - Why
requirements.txtis copied before the source code
- Why exec form for
-
Project Structure
-
requirements.txt -
Environment Variables and Secrets
-
Building the Image
-
Single Uvicorn Process vs Multiple Workers
- One process per container (Kubernetes, Docker Swarm)
- Multiple workers per container (single server, Docker Compose)
- Behind a reverse proxy
-
Docker Compose: Full Stack
-
Pushing to a Container Registry
-
Common Mistakes to Avoid
-
Practice Challenge
-
Frequently Asked Questions
