Escribe para buscar…

Deploy

Esta página todavía no se ha traducido — se muestra en su 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 leyendo una vista previa.

Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión