Skip to content

FastAPI Setup with Docker

This setup creates the smallest FastAPI project. The app runs inside Docker, installs Python dependencies inside the container, and exposes a basic route.

Create a small project folder with one FastAPI app file, one requirements file, one Dockerfile, one Compose file.

01-basic-route/
app/
main.py
requirements.txt
Dockerfile
compose.yaml
README.md
Terminal window
mkdir 01-basic-route
cd 01-basic-route
mkdir app

Create the main FastAPI application file at app/main.py. This file defines the FastAPI application instance and two simple GET routes. The root route returns a basic message and the health route returns a status response.

app/main.py
from fastapi import FastAPI
app = FastAPI(title="01 Basic Route")
@app.get("/")
def home():
return {
"message": "Hello from FastAPI running in Docker"
}
@app.get("/health")
def health():
return {
"status": "ok"
}

Create the dependency file at requirements.txt. This file installs FastAPI and Uvicorn. FastAPI is the framework and Uvicorn is the ASGI server that runs the application.

requirements.txt
fastapi
uvicorn[standard]

Create the Dockerfile at the project root. The Dockerfile uses a small Python image, creates a virtual environment inside the container, installs the dependencies, copies the project files, and starts Uvicorn.

Dockerfile
FROM python:3.12-slim
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

The app.main:app value means the app folder, the main.py file, and the FastAPI instance named app.

Create the Docker Compose file at compose.yaml. Docker Compose builds the backend container, maps port 8000 from the container to the host, and mounts the project folder into the container for live reload during development.

compose.yaml
services:
backend:
build: .
container_name: fastapi-01-basic-route
ports:
- "8000:8000"
volumes:
- .:/app

Run Docker Compose from inside the project folder. The build step creates the image, installs the dependencies, and starts the FastAPI server.

Terminal window
docker compose up --build

The server should show a Uvicorn startup message.

Uvicorn running on http://0.0.0.0:8000

Open the root route in the browser to confirm that the FastAPI app returns JSON.

http://localhost:8000
{
"message": "Hello from FastAPI running in Docker"
}

Open the health route to confirm that the app is running.

http://localhost:8000/health
{
"status": "ok"
}

Open the automatic FastAPI documentation page.

http://localhost:8000/docs

Stop the running container from the terminal where Docker Compose is running or shut it down from another terminal.

Terminal window
# Press this in the running terminal
CTRL + C
# Or run this from another terminal
docker compose down