Here’s a straightforward guide to containerizing a FastAPI application.
First, create a basic FastAPI application (main.py):


from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Create a requirements.txt:


fastapi
uvicorn

Create a Dockerfile:


FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

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

Build and run the container:


docker build -t fastapi-app .
docker run -d -p 8000:8000 fastapi-app

Your FastAPI application is now running in Docker and accessible at http://localhost:8000. The API documentation is available at /docs.
For development, mount your code as a volume to enable hot-reload:


docker run -d -p 8000:8000 -v $(pwd):/app fastapi-app uvicorn main:app --host 0.0.0.0 --port 8000 --reload

This configuration provides a production-ready container while remaining minimal and secure. The slim Python base image reduces the container size, and running as a non-root user would be a recommended security practice for production.

Categorized in:

Short answers,

Last Update: 19/01/2025