How to Use Docker Compose with FastAPI: Simple Setup Guide
Use
docker-compose.yml to define services including your FastAPI app and its dependencies. Build a Docker image for FastAPI with a Dockerfile, then run docker-compose up to start the app and linked services together.Syntax
A docker-compose.yml file defines multiple services to run together. Each service has a name and configuration like build (to build an image), ports (to expose ports), and volumes (to share files).
The FastAPI app needs a Dockerfile that specifies the base image, copies code, installs dependencies, and runs the app with uvicorn.
yaml
version: '3.8' services: fastapi: build: . ports: - "8000:8000" volumes: - .:/app command: uvicorn main:app --host 0.0.0.0 --port 8000
Example
This example shows a simple FastAPI app running with Docker Compose. The Dockerfile builds the app image, and docker-compose.yml runs it exposing port 8000.
plaintext
# main.py from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"message": "Hello from FastAPI with Docker Compose!"} # Dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] # requirements.txt fastapi uvicorn[standard] # docker-compose.yml version: '3.8' services: fastapi: build: . ports: - "8000:8000" volumes: - .:/app command: uvicorn main:app --host 0.0.0.0 --port 8000
Output
INFO: Started server process [1]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Common Pitfalls
- Not exposing the correct port in
docker-compose.ymlcauses the app to be unreachable. - Forgetting to set
--host 0.0.0.0in theuvicorncommand makes the app listen only inside the container. - Not mounting volumes during development means code changes won’t reflect without rebuilding the image.
- Missing dependencies in
requirements.txtleads to runtime errors.
yaml
# Wrong: Missing host option command: uvicorn main:app --port 8000 # Right: Include host to listen on all interfaces command: uvicorn main:app --host 0.0.0.0 --port 8000
Quick Reference
Remember these key points when using Docker Compose with FastAPI:
- Use
buildto create the FastAPI image from yourDockerfile. - Expose port 8000 with
ports: - "8000:8000"to access the app from your machine. - Use
volumesto sync code changes during development. - Run
uvicornwith--host 0.0.0.0so the app is reachable outside the container.
Key Takeaways
Always expose port 8000 and set uvicorn host to 0.0.0.0 in Docker Compose for FastAPI.
Use a Dockerfile to build your FastAPI app image with dependencies installed.
Mount volumes in development to see code changes without rebuilding the image.
Run your app with docker-compose up to start all services together easily.