← All Tutorials
FrameworksFeb 10, 202610 min read

Deploy a Python FastAPI Application

Build and deploy a production-ready FastAPI application with Docker on Rackline.

Introduction

FastAPI is the leading Python web framework for building APIs, combining automatic OpenAPI documentation with high performance via async support. This tutorial covers building a FastAPI application, containerizing it with Docker, and deploying it to a Rackline droplet with proper production configuration.

Prerequisites

  • A Rackline account with an active droplet (2 GB RAM recommended)
  • Python 3.13 installed locally
  • Docker installed locally for testing

Step 1 — Create Your FastAPI Application

Set up a new project with a virtual environment and install FastAPI along with Uvicorn as the ASGI server. We will also use Pydantic v2 for data validation, which comes bundled with FastAPI.

bash
mkdir my-fastapi-app && cd my-fastapi-app
python3.13 -m venv .venv
source .venv/bin/activate

pip install fastapi[standard] uvicorn[standard]
pip freeze > requirements.txt

Step 2 — Write the Application Code

Create a main.py file with your API endpoints. FastAPI uses Python type hints to automatically generate request validation and OpenAPI documentation. The example below creates a simple items API with CRUD operations.

python
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="My Rackline API", version="1.0.0")

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float

items: dict[int, Item] = {}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

@app.post("/items/{item_id}", status_code=201)
async def create_item(item_id: int, item: Item):
    if item_id in items:
        raise HTTPException(status_code=409, detail="Item exists")
    items[item_id] = item
    return item

@app.get("/items")
async def list_items():
    return items

Step 3 — Containerize with Docker

Create a multi-stage Dockerfile that produces a lean production image. Using a slim base image keeps the final container under 100 MB and reduces attack surface.

dockerfile
# Dockerfile
FROM python:3.13-slim AS base

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", "--workers", "4"]

Pro Tip

Set --workers to 2x the number of CPU cores available on your droplet. For a 2-vCPU droplet, use 4 workers.

Step 4 — Deploy to Rackline

Push your Docker image to the Rackline container registry and deploy it. Rackline handles SSL termination, health checks, and automatic restarts if your container crashes.

bash
# Build and push to Rackline registry
rackline registry login
docker build -t registry.rackline.net/my-fastapi-app:latest .
docker push registry.rackline.net/my-fastapi-app:latest

# Deploy the container
rackline deploy --image registry.rackline.net/my-fastapi-app:latest \
  --port 8000 \
  --health-check /health \
  --environment production

Step 5 — Configure Environment and Monitoring

Set environment variables for your production deployment and enable monitoring. Rackline automatically collects container logs and metrics, which you can view in the dashboard or stream via the CLI.

bash
# Set production environment variables
rackline env set DATABASE_URL="postgresql://..." --environment production
rackline env set SECRET_KEY="your-secret-key" --environment production

# Enable monitoring alerts
rackline monitor alerts create \
  --metric cpu \
  --threshold 80 \
  --channel email

# Stream logs
rackline logs --follow --tail 100

Pro Tip

Visit /docs on your deployed API to access the auto-generated Swagger UI, and /redoc for the ReDoc documentation.

Conclusion

Your FastAPI application is now running in a Docker container on Rackline with health checks, monitoring, and automatic SSL. For high-traffic applications, consider adding a Redis cache and setting up horizontal scaling with load balancing.