Escriu per cercar…

Deploy

Aquesta pàgina encara no s'ha traduït — es mostra en l'idioma original:English

Introduction

Deployment

To deploy an application means to perform the necessary steps to make it available to the users.

For a web API, it normally involves putting it in a remote machine, with a server program that provides good performance, stability, etc, so that your users can access the application efficiently and without interruptions or problems.

This is in contrast to the development stages, where you are constantly changing the code, breaking it and fixing it, stopping and restarting the development server, etc.

Serving a FastAPI application behind Nginx is the “gold standard” for production. Nginx acts as a reverse proxy, handling SSL termination, buffering, and load balancing, while an ASGI server like Uvicorn (often managed by Gunicorn) runs your actual Python code.

Get Started

Here is your step-by-step guide to getting it live.

Prepare Your FastAPI Application

First, ensure you have your application ready and the necessary production servers installed.

shell
uv install fastapi uvicorn gunicorn

Create a simple main.py for testing:

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"status": "FastAPI is running behind Nginx!"}

Configure Gunicorn with Uvicorn Workers

In production, we use Gunicorn to manage multiple Uvicorn worker processes. This makes your app more resilient.

Test it manually first:

shell
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 127.0.0.1:8000
  • -w 4: Runs 4 worker processes.
  • -k uvicorn.workers.UvicornWorker: Tells Gunicorn to use Uvicorn as the class.

Create a Systemd Service

You don’t want to manually start your app every time the server reboots. Let’s automate it.

Create a service file: sudo nano /etc/systemd/system/fastapi_app.service

Paste the following configuration:

ini
[Unit]
Description=Gunicorn instance to serve FastAPI
After=network.target

[Service]
User=your-user
Group=www-data
WorkingDirectory=/home/your-user/app
ExecStart=/home/your-user/app/venv/bin/gunicorn \
    -w 4 \
    -k uvicorn.workers.UvicornWorker \
    -b unix:app.sock main:app

[Install]
WantedBy=multi-user.target

Estàs llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió