Your FastAPI app runs perfectly on your laptop. Then it goes to a server with a different Python version, a missing system library, and an environment variable nobody wrote down. Suddenly it doesn’t start.
Docker solves this by packaging your app, its dependencies and the runtime into one image that runs the same way everywhere: your laptop, a teammate’s machine, a cloud VM, Azure Container Apps, AWS, Google Cloud Run or Kubernetes.
This guide takes a simple FastAPI app and turns it into a clean, production-ready container.
The app
Here’s a minimal project:
taskapi/
├── app/
│ ├── __init__.py
│ └── main.py
├── requirements.txt
├── Dockerfile
└── .dockerignore
app/main.py:
from fastapi import FastAPI
app = FastAPI(title="Task API")
@app.get("/health")
def health():
return {"status": "ok"}
@app.get("/tasks")
def list_tasks():
return [{"id": 1, "title": "Write Dockerfile", "done": True}]
requirements.txt:
fastapi>=0.115
uvicorn[standard]>=0.30
Pin exact versions for production builds (for example with pip freeze or a lock file) so every build is reproducible.
Step 1: Write the Dockerfile
# Use a slim official Python image
FROM python:3.12-slim
# Don't write .pyc files; send logs straight to the terminal
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app
# Install dependencies first, so Docker can cache this layer
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code
COPY app ./app
# Create and switch to a non-root user
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
# Basic health check using Python (no curl needed in the slim image)
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')" || exit 1
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Why it’s written this way
Slim base image. python:3.12-slim is much smaller than the full image, which means faster downloads and fewer packages to patch.
Dependencies before code. Docker caches each step. Because requirements.txt changes less often than your code, copying and installing it first means rebuilding after a code change takes seconds instead of reinstalling every package.
--no-cache-dir. Stops pip from keeping downloaded packages inside the image.
PYTHONUNBUFFERED=1. Makes logs appear immediately in docker logs.
Non-root user. If someone exploits your app, they don’t get root inside the container. This is a simple, important security step.
--host 0.0.0.0. Inside a container, 127.0.0.1 would only accept connections from inside the container itself. 0.0.0.0 listens on all interfaces so Docker can forward traffic in.
Exec-form CMD. Using the JSON array form means Uvicorn receives shutdown signals properly, so the container stops cleanly.
Step 2: Add a .dockerignore
Without it, Docker sends everything in the folder to the build, including virtual environments, Git history and secrets.
.venv
venv
__pycache__
*.pyc
.git
.env
.pytest_cache
tests
Dockerfile
docker-compose.yml
Keeping .env out of the image is especially important. Secrets should be supplied at runtime, never baked into images.
Step 3: Build and run
docker build -t taskapi:1.0 .
docker run -d --name taskapi -p 8000:8000 taskapi:1.0
-p 8000:8000 maps port 8000 on your machine to port 8000 in the container. Open http://localhost:8000/docs to see FastAPI’s interactive documentation.
Useful commands:
docker ps # running containers (and health status)
docker logs -f taskapi # follow logs
docker exec -it taskapi sh # open a shell inside the container
docker stop taskapi && docker rm taskapi
Step 4: Pass configuration with environment variables
Never hard-code database passwords or API keys. Read them from the environment:
import os
DATABASE_URL = os.environ["DATABASE_URL"]
Then supply them when running:
docker run -d -p 8000:8000 \
-e DATABASE_URL="postgresql://app:secret@db:5432/tasks" \
taskapi:1.0
Or with an env file that stays out of Git:
docker run -d -p 8000:8000 --env-file .env taskapi:1.0
In the cloud, use the platform’s secret store (Azure Key Vault, AWS Secrets Manager, Google Secret Manager) rather than plain env files.
Step 5: Add a database with Docker Compose
Most real APIs need a database. Docker Compose runs several containers together:
# docker-compose.yml
services:
api:
build: .
ports:
- "8000:8000"
environment:
DATABASE_URL: postgresql://app:secret@db:5432/tasks
depends_on:
db:
condition: service_healthy
db:
image: postgres:17
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: tasks
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d tasks"]
interval: 5s
retries: 10
volumes:
pgdata:
docker compose up -d --build
docker compose logs -f api
docker compose down # stop (data stays in the volume)
Notice the API connects to host db, the service name. Compose creates a private network where containers find each other by name. The named volume pgdata keeps database data when containers are recreated.
The passwords above are fine for local development only. Use proper secrets for anything else.
Step 6: Production touches
Multiple workers. One Uvicorn process uses one CPU core. For more throughput, either run more container replicas (the usual approach on container platforms) or start several workers:
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
Behind a reverse proxy. If Nginx, Traefik or a cloud load balancer terminates HTTPS in front of your app, add --proxy-headers so FastAPI sees the original client IP and scheme.
Tag images properly. Use version tags like taskapi:1.4.2 or the Git commit hash, not just latest, so you know exactly what’s running and can roll back.
Scan images. Tools like Docker Scout, Trivy or Grype find known vulnerabilities in your base image and packages. Rebuild regularly to pick up security patches.
Keep images small. If you need build tools to compile packages, use a multi-stage build: compile in one stage, copy only the results into a clean slim image.
Common problems
“Connection refused” from the browser. Usually the app is listening on 127.0.0.1 inside the container. Use --host 0.0.0.0, and check the -p mapping.
Changes not showing up. You need to rebuild the image after code changes (docker build or docker compose up --build). For development, mount your code as a volume and run Uvicorn with --reload.
“Permission denied” writing files. The non-root user can’t write to folders owned by root. Create writable folders and chown them in the Dockerfile, or write to a mounted volume.
Huge image size. Check for a missing .dockerignore, a full (non-slim) base image, or leftover build tools.
Where to run it
Once it’s an image, you can push it to a registry (Docker Hub, GitHub Container Registry, Azure Container Registry, Amazon ECR) and run it on:
- any Linux server with Docker
- Azure Container Apps or App Service for Containers
- AWS App Runner or ECS with Fargate
- Google Cloud Run
- Kubernetes, when you need it
Your next step
You’ve packaged a FastAPI app into a secure, cache-friendly image, configured it with environment variables, and run it alongside PostgreSQL with Docker Compose. The same image now runs identically everywhere.
The natural next step is automating it: build, test, scan and push the image on every commit with a CI/CD pipeline, so deployment becomes a routine, one-click event.
Leave a Comment