Docker is a platform that allows you to package an application and all its dependencies into a container. A container is a lightweight, standalone, and executable unit of software that runs the same way, regardless of the environment (development, staging, or production).
Why Dockerize a FastAPI Application?
1. Environment Consistency
Docker ensures your FastAPI app runs the same on every machine—no more "works on my machine" problems.
2. Easy Deployment
Package your app with all dependencies, then deploy it anywhere (cloud, VM, server) with just one command.
3. Isolation
Your app runs in its own container, isolated from other services or apps on the system.
4. Scalability
Docker works seamlessly with container orchestration tools (like Kubernetes), making it easier to scale FastAPI apps.
5. Developer Productivity
Simplifies onboarding—new developers can start the app with just docker-compose up
.
Project Structure
your-fastapi-app/
app/
main.py
... # your modules, routers, etc.
requirements.txt
Dockerfile
docker-compose.yml # (optional but recommended)
1. Dockerfile
# Use an official Python image
FROM python:3.10
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install ffmpeg and clean up in a single layer to reduce image size
RUN apt-get update && \
apt-get install -y ffmpeg && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements1.txt .
RUN pip install --no-cache-dir --upgrade -r requirements1.txt
# Copy the specified folders and files into the container
COPY api/ api/
COPY config/ config/
COPY README.md .
COPY main.py .
# or you can copy root folder as well like
#COPY ./app /app
# Run the app
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# Set up Gunicorn to run the application. Adjust the Gunicorn configuration as needed.
# CMD ["gunicorn", "main:app", "--bind", "0.0.0.0:80", "--workers", "1", "--worker-class", "uvicorn.workers.UvicornWorker", "--log-file", "-", "--max-requests", "1000", "--max-requests-jitter", "50"]
2. requirements.txt
Make sure you include your dependencies like:
fastapi
uvicorn[standard]
pydantic
# Add more as needed
You can export this with:
pip freeze > requirements.txt
3. main.py
(basic example)
Inside app/main.py
:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "FastAPI Dockerized!"}
4. docker-compose.yml
(Optional but useful)
version: "3.9"
services:
fastapi:
build: .
ports:
- "8000:8000"
volumes:
- ./app:/app
environment:
- PYTHONUNBUFFERED=1
How to Run
Build and Run with Docker:
docker build -t fastapi-app .
docker run -d -p 8000:8000 fastapi-app
OR with Docker Compose:
docker-compose up --build
Then open: http://localhost:8000
Improvement
- Use
.dockerignore
to exclude files like__pycache__
,.env
, etc. - Use
alembic
if you're managing a DB. - Use
gunicorn
+uvicorn.workers.UvicornWorker
in production for better performance.