Forem

Olasubomi Onasanwo
Olasubomi Onasanwo

Posted on

Deploying a FastAPI Application with Docker and Nginx: A Comprehensive Guide

This project demonstrates the deployment of a modern web API using FastAPI, a high-performance Python web framework, integrated with industry-standard DevOps practices. The core application is a book management system that allows users to perform CRUD (Create, Read, Update, Delete) operations on a collection of books, with each book containing details such as title, author, publication year, and genre. The system maintains data consistency through a structured schema and provides RESTful endpoints for interacting with the book inventory.
The deployment architecture showcases the implementation of containerization using Docker and reverse proxy configuration using Nginx, essential components in modern web application deployment. The solution utilizes Docker Compose for container orchestration, managing two main services: the FastAPI application and an Nginx reverse proxy. This setup ensures proper request routing, header management, and service isolation, while maintaining high availability and scalability. The deployment process includes comprehensive configuration of server headers, network settings, and proper integration between the FastAPI service and Nginx proxy, demonstrating a production-ready implementation that follows DevOps best practices.

Prerequisites

AWS EC2 instance (Ubuntu 22.04)
Basic knowledge of Python, Docker, and Nginx
Domain name (optional)

System Architecture
Our deployment stack consists of:

FastAPI application serving the API
Nginx acting as a reverse proxy
Docker containers for isolation and portability
Docker Compose for service orchestration

Step 1: Server Setup
1.1 Launch EC2 Instance

Launch Ubuntu 22.04 EC2 instance
Configure security groups:
HTTP (80) : 0.0.0.0/0
HTTPS (443) : 0.0.0.0/0
SSH (22) : Your IP

1.2 Connect to Server
ssh -i your-key.pem ubuntu@your-ec2-public-ip

1.3 Update System
sudo apt update
sudo apt upgrade -y

Step 2: Installing Required Software
2.1 Install Python and Virtual Environment

Install Python 3

sudo apt install python3 python3-pip -y

Install venv

sudo apt install python3.10-venv -y

Create virtual environment

python3 -m venv venv

Activate virtual environment

source venv/bin/activate

2.2 Install Docker and Docker Compose

Install Docker

sudo apt install docker.io -y

Install Docker Compose

sudo apt install docker-compose -y

Add user to docker group

sudo usermod -aG docker $USER

Verify installations

docker --version
docker-compose --version

Step 3: Application Setup
3.1 Clone and Configure Project

Clone project repository

git clone your-repository-url
cd fastapi-book-project

Create project structure

mkdir -p api/db api/routes

3.2 Create Application Files
main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.router import router

app = FastAPI(
title="Book Management API",
description="A simple API for managing books",
version="1.0.0"
)

app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_credentials=True,
allow_methods=["
"],
allow_headers=["*"],
)

app.include_router(router)

api/router.py
from fastapi import APIRouter
from api.routes import books

router = APIRouter()

router.include_router(
books.router,
prefix="/api/v1/books",
tags=["books"]
)

Step 4: Docker Configuration
4.1 Create Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

4.2 Create docker-compose.yml
version: '3.8'
services:
fastapi-app:
build: .
container_name: fastapi_app
restart: always
networks:
- app_network

nginx:
image: nginx:alpine
container_name: fastapi_nginx
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- fastapi-app
networks:
- app_network

networks:
app_network:
driver: bridge

Step 5: Nginx Configuration
5.1 Create nginx.conf
server {
listen 80;
server_name your-domain;

proxy_hide_header Server;
add_header Server nginx always;

location /api/v1/books {
    proxy_pass http://fastapi-app:8000/api/v1/books/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

location / {
    proxy_pass http://fastapi-app:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}
Enter fullscreen mode Exit fullscreen mode

}

Step 6: Deployment
6.1 Build and Start Services

Build images

docker-compose build

Start services

docker-compose up -d

Verify services

docker-compose ps

6.2 Check Logs

Check FastAPI logs

docker-compose logs fastapi-app

Check Nginx logs

docker-compose logs nginx

Step 7: Testing
7.1 API Endpoint Testing

Test list endpoint

curl http://your-domain/api/v1/books/

Test single book endpoint

curl http://your-domain/api/v1/books/1

Test server headers

curl -I http://your-domain/api/v1/books/

7.2 Browser Testing
Navigate to http://your-domain/docs
Test endpoints through Swagger UI

Step 8: Maintenance and Monitoring
8.1 View Container Stats
docker stats
8.2 Monitor Logs
docker-compose logs -f

8.3 Backup Configuration

Backup important files

tar -czf backup.tar.gz docker-compose.yml nginx.conf Dockerfile

Best Practices

Security

Keep Docker and system packages updated
Use specific container versions
Implement proper firewall rules

Performance

Enable Nginx caching when appropriate
Monitor resource usage
Implement rate limiting

Maintenance

Regular backups
Log rotation
Health checks

Conclusion
This deployment architecture provides a robust, scalable solution for hosting FastAPI applications. The combination of Docker containers and Nginx reverse proxy ensures:

Isolated application environment
Proper request handling
Scalability options
Easy maintenance

Regular monitoring and maintenance will ensure optimal performance and reliability of your deployed application.

Top comments (0)