FastAPI Deployment Guide for CloudPanel 2024 Ubuntu (Non ARM)

FastAPI Deployment Guide for CloudPanel

Table of Contents

  1. Prerequisites
  2. CloudPanel Setup
  3. Project Structure
  4. FastAPI Application Setup
  5. Virtual Environment Configuration
  6. Gunicorn Setup
  7. Nginx Configuration
  8. SSL Configuration
  9. Deployment Steps
  10. Troubleshooting

1. Prerequisites

  • CloudPanel installed on your server
  • Python 3.8+ installed
  • Basic knowledge of Linux commands
  • Domain name pointed to your server

2. CloudPanel Setup

CloudPanel Directory Structure

/home/your-user/htdocs/
└── your-domain.com/
    ├── private/
    │   ├── python/
    │   └── logs/
    └── public/
        └── static/

Creating a New Site in CloudPanel

  1. Log in to CloudPanel UI (typically at https://your-server-ip:8443)
  2. Navigate to “Sites” in the left sidebar
  3. Click “Add Site”
  4. Fill in the following details:
    • Domain Name: your-domain.com
    • Technology Stack: Python
    • Python Version: 3.8+ (recommended)
    • Document Root: /public
    • SSL: Enable (recommended)

3. Project Structure

After site creation, organize your FastAPI project like this:

/home/your-user/htdocs/your-domain.com/
├── private/
│   ├── python/
│   │   ├── venv/
│   │   ├── app/
│   │   │   ├── __init__.py
│   │   │   ├── main.py
│   │   │   ├── routers/
│   │   │   ├── models/
│   │   │   └── dependencies/
│   │   ├── requirements.txt
│   │   └── gunicorn_config.py
│   └── logs/
│       ├── access.log
│       └── error.log
└── public/
    └── static/

4. FastAPI Application Setup

Create main.py

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# Mount static files
app.mount("/static", StaticFiles(directory="/home/your-user/htdocs/your-domain.com/public/static"), name="static")

@app.get("/")
async def root():
    return {"message": "Hello from FastAPI"}

Create requirements.txt

fastapi==0.104.1
uvicorn==0.24.0
gunicorn==21.2.0
python-multipart==0.0.6

5. Virtual Environment Configuration

cd /home/your-user/htdocs/your-domain.com/private/python
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

6. Gunicorn Setup

Create gunicorn_config.py

import multiprocessing

bind = "unix:/home/your-user/htdocs/your-domain.com/private/python/app.sock"
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "uvicorn.workers.UvicornWorker"
timeout = 120
keepalive = 5
errorlog = "/home/your-user/htdocs/your-domain.com/private/logs/error.log"
accesslog = "/home/your-user/htdocs/your-domain.com/private/logs/access.log"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

7. Nginx Configuration

CloudPanel automatically manages Nginx configuration, but here’s the recommended setup:

server {
......
    
    location / {
        proxy_pass http://unix:/home/your-user/htdocs/your-domain.com/private/python/app.sock;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /static {
        alias /home/your-user/htdocs/your-domain.com/public/static;
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
}

8. SSL Configuration

  1. In CloudPanel UI, go to Sites > your-domain.com
  2. Click “SSL/TLS”
  3. Choose either:
    • Let’s Encrypt (free, automatic renewal)
    • Custom SSL certificate
  4. Follow the wizard to complete SSL setup

9. Deployment Steps

  1. Upload your FastAPI application:
# Assuming you're using git
cd /home/your-user/htdocs/your-domain.com/private/python
git clone your-repository-url .
  1. Set up virtual environment and install dependencies:
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
  1. Start Gunicorn:
gunicorn app.main:app -c gunicorn_config.py --daemon
  1. Set up systemd service for automatic startup:
# /etc/systemd/system/fastapi-your-domain.service
[Unit]
Description=FastAPI application for your-domain.com
After=network.target

[Service]
User=your-user
Group=your-user
WorkingDirectory=/home/your-user/htdocs/your-domain.com/private/python
Environment="PATH=/home/your-user/htdocs/your-domain.com/private/python/venv/bin"
ExecStart=/home/your-user/htdocs/your-domain.com/private/python/venv/bin/gunicorn app.main:app -c gunicorn_config.py
Restart=always

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable fastapi-your-domain
sudo systemctl start fastapi-your-domain

10. Troubleshooting

Common Issues and Solutions

  1. Permission Issues
sudo chown -R your-user:your-user /home/your-user/htdocs/your-domain.com/
chmod -R 755 /home/your-user/htdocs/your-domain.com/
  1. Socket Connection Issues
  • Check socket file exists and has correct permissions
  • Verify Gunicorn is running: ps aux | grep gunicorn
  • Check logs: tail -f /home/your-user/htdocs/your-domain.com/private/logs/error.log
  1. Static Files Not Loading
  • Verify static directory permissions
  • Check Nginx configuration for correct static file path
  • Clear browser cache
  1. 502 Bad Gateway
  • Check if Gunicorn is running
  • Verify socket file permissions
  • Check application logs for Python errors

Maintenance Commands

# Restart FastAPI application
sudo systemctl restart fastapi-your-domain

# Check application status
sudo systemctl status fastapi-your-domain

# View logs
tail -f /home/your-user/htdocs/your-domain.com/private/logs/error.log
tail -f /home/your-user/htdocs/your-domain.com/private/logs/access.log

Common CloudPanel-Specific Notes

  1. The nginx configuration is managed by CloudPanel in the UI, but you can add custom configurations through the CloudPanel interface under Sites > your-domain.com > Vhost.

  2. Python versions can be switched in the CloudPanel UI under Sites > your-domain.com > PHP Version (despite the name, it handles Python versions too).

  3. Always check the CloudPanel logs in addition to your application logs when troubleshooting:

    tail -f /var/log/your-app/logs/error.log
    
  4. When updating your application, you may need to:

    # Restart the FastAPI service
    sudo systemctl restart fastapi-your-domain