Deploy
Introduction
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.
Create a simple main.py for testing:
=
return 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:
-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:
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ó