Table of Contents
In today’s software development landscape, building scalable and efficient APIs is crucial. FastAPI, a modern web framework for Python, offers high performance and easy integration. Combining FastAPI with Docker and Docker Compose allows developers to create portable, scalable, and maintainable APIs. This tutorial guides you through setting up a FastAPI application using Docker Compose.
Prerequisites
- Python 3.8 or higher installed on your machine
- Docker and Docker Compose installed
- Basic knowledge of Python and Docker
Creating the FastAPI Application
Start by creating a project directory and initializing a Python environment. Inside your project folder, create a virtual environment and install FastAPI along with Uvicorn, an ASGI server.
Run the following commands:
mkdir fastapi-docker
cd fastapi-docker
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
pip install fastapi uvicorn
Next, create a file named main.py with the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI with Docker!"}
Creating the Dockerfile
In the project directory, create a Dockerfile to containerize your FastAPI app:
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"]
Also, create a requirements.txt file to specify dependencies:
fastapi
uvicorn
Setting Up Docker Compose
Create a docker-compose.yml file to define your service:
version: "3.8"
services:
fastapi:
build: .
ports:
- "8000:8000"
volumes:
- ./:/app
environment:
- PYTHONPATH=/app
Building and Running the Application
Use Docker Compose to build and start your FastAPI application:
docker-compose up --build
Once running, access your API at http://localhost:8000. You should see the JSON response:
{"message": "Hello, FastAPI with Docker!"}
Conclusion
By following this tutorial, you have set up a scalable FastAPI application using Docker and Docker Compose. This setup provides a solid foundation for deploying robust APIs in development and production environments. You can extend this configuration by adding databases, background workers, or other microservices as needed.