Skip to content

How to Deploy FastAPI on VPS

Prerequisites

Before we begin, make sure you have the following: - A VPS (Virtual Private Server) running a modern Linux distribution (Ubuntu 22.04 or later recommended) - Basic understanding of Docker and containerization - A FastAPI application ready for deployment - SSH access to your VPS - A domain name (optional, but recommended for SSL)

Step 1: Preparing Your FastAPI Application

Dockerizing Your FastAPI Application

First, let's create a Dockerfile for your FastAPI project. Here's a generic template:

# Use an official Python runtime as a parent image
FROM python:3.11-slim

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 8000 available to the world outside this container
EXPOSE 8000

# Define environment variable
ENV NAME FastAPIApp

# Run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Create a requirements.txt file listing all your project dependencies:

fastapi==0.95.1
uvicorn==0.22.0
# Add other dependencies here

Docker Compose Configuration

Create a docker-compose.yml file to manage your application's containerization:

version: '3.8'

services:
  web:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - .:/app
    environment:
      - ENV=production

Step 2: Setting Up Caddy Server

Caddy is an excellent modern web server with automatic HTTPS that simplifies our deployment process. We'll use Caddy as a reverse proxy to route traffic to our FastAPI application.

Caddyfile Configuration

Create a Caddyfile in your project root:

your-domain.com {
    reverse_proxy web:8000
    encode gzip
    log {
        output file /var/log/caddy/access.log
        format json
    }
}

Replace your-domain.com with your actual domain name.

Step 3: Complete Docker Compose Setup

Update your docker-compose.yml to include Caddy:

version: '3.8'

services:
  web:
    build: .
    expose:
      - "8000"
    volumes:
      - .:/app
    environment:
      - ENV=production

  caddy:
    image: caddy:2.6-alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - web

volumes:
  caddy_data:
  caddy_config:

Step 4: Deployment on VPS

Connecting to Your VPS

Use SSH to connect to your VPS:

ssh username@your-server-ip

Installing Docker and Docker Compose

# Update package lists
sudo apt update

# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

# Install Docker Compose
sudo apt install docker-compose

Transferring Project Files

Use scp or rsync to transfer your project files:

scp -r /path/to/local/project username@your-server-ip:/path/on/server

Deployment Commands

Navigate to your project directory and run:

# Build and start containers
docker-compose up -d --build

# View logs
docker-compose logs -f

Step 5: Security Considerations

Firewall Configuration

Configure UFW (Uncomplicated Firewall):

sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable

Environment Variables

Use Docker secrets or environment files to manage sensitive information like API keys and database credentials.

Troubleshooting Common Issues

  1. Port Conflicts: Ensure no other services are using ports 80 and 443
  2. Permission Issues: Run Docker commands with sudo or add your user to the docker group
  3. SSL Certificate Problems: Verify domain configuration and DNS settings

Performance and Scaling

  • Use multi-stage Docker builds to reduce image size
  • Implement container orchestration with Kubernetes for larger applications
  • Consider using Docker Swarm for simple scaling needs

Next Steps

  • Set up continuous integration/continuous deployment (CI/CD)
  • Implement monitoring and logging
  • Explore advanced containerization techniques