Sign In
Sign In

Installing and Configuring a FastAPI Website on a VDS/VPS

Installing and Configuring a FastAPI Website on a VDS/VPS
Hostman Team
Technical writer
Python
16.07.2024
Reading time: 11 min

FastAPI is one of the most popular frameworks for building compact and fast HTTP servers in Python, released in 2018. It is built on several lower-level libraries:

  • Pydantic: A data validation library for Python.

  • Starlette: An ASGI (Asynchronous Server Gateway Interface) toolkit designed to support asynchronous functions in Python.

In this tutorial, we will explore how to manually deploy a web application created with FastAPI on a local or remote Unix machine. For this, we need several basic components:

  • Python: The programming language compiler.

  • FastAPI: A Python package.

  • Nginx: A web server with the appropriate configuration file.

  • Uvicorn: An ASGI server for Python.

  • Systemd: A system utility for managing running services.

Our web application's architecture will be as follows:

First, the Python code using the FastAPI package is run as an ASGI server via the Uvicorn web server. Then, Nginx is launched as a proxy server, which will forward all incoming requests to the already running Uvicorn server. Both servers, Uvicorn and Nginx, will be managed by the system utility Systemd. Nginx will handle user requests on port 80 (the standard port for HTTP protocol) and forward them to port 8000 (typically free for TCP/UDP connections) on the Uvicorn server with the FastAPI application.

To deploy this technology stack, we will need a cloud virtual server with the Ubuntu operating system.

Installing Python

First, check if Python is already installed on the system:

python3 --version

Next, update the list of available packages:

sudo apt update

Then install the latest version of Python and a few related dependencies: the package manager, a library for high-level types, and a module for creating virtual environments.

sudo apt install python3 python3-pip python3-dev python3-venv

Now, if you run Python, it should start the interpreter:

python3

To verify, enter some simple code and execute it:

print("Hello, Hostman")

The output in the console should be:

Hello, Hostman

Installing and Configuring the Nginx Server

In our example, Nginx will act as a reverse proxy server, receiving user requests and passing them to the Uvicorn ASGI server for the FastAPI application.

Installation

We have a detailed guide on how to install the Nginx web server on the Ubuntu operating system. 

First, update the list of repositories:

sudo apt update

Then, download and install Nginx:

sudo apt install nginx

Next, adjust the system firewall UFW (Uncomplicated Firewall) to allow HTTP connections on port 80:

sudo ufw allow 'Nginx HTTP'

Configuration

The Nginx configuration file, nginx.conf, is located in the /etc/nginx/ directory. We will completely overwrite its contents with minimal settings required to forward requests to FastAPI:

daemon on; # Nginx will run as a background service
worker_processes 2;
user www-data;

events {
	use epoll;
	worker_connections 1024;
}

error_log /var/log/nginx/error.log;

http {
	server_tokens off;
	include mime.types;
	charset utf-8;


	access_log logs/access.log combined;

	server {
		listen 80;
		server_name www.DOMAIN.COM DOMAIN.COM;

		# Replace DOMAIN.COM with your server's address
		# Or you can use localhost

		location / {
			proxy_pass http://127.0.0.1:8000; # The port should match the Uvicorn server port
			proxy_set_header Host $host; # Pass the Host header with the target IP and port of the server
			proxy_set_header X-Real-IP $remote_addr; # Pass the header with the user's IP address
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Pass the entire chain of addresses the request has passed through
		}
	}
}

Note that we have simplified the configuration file structure by avoiding the use of the /etc/nginx/sites-available/ and /etc/nginx/sites-enabled/ directories, as well as additional files from /etc/nginx/conf.d/. This minimal configuration is not only crucial for our example but also helps eliminate unnecessary server elements and improve server security and understanding.

To check the syntax in the configuration file, run the following command:

sudo nginx -t

To apply the new configuration, you need to restart the web server manually:

sudo systemctl restart nginx

For reference, there is another command that restarts Nginx, gracefully ending its processes:

sudo systemctl reload nginx

Creating a Simple FastAPI Application

Next, let's create a FastAPI app to use in this article.

Project directory

To start, we will create a directory for our FastAPI application under the system directory /var, which is recommended for hosting web server files:

mkdir /var/www/fastapp

Next, navigate into the newly created directory:

cd /var/www/fastapp

Virtual environment

We will now set up a local isolated Python virtual environment, which is why we installed the python3-venv package earlier:

python3 -m venv venv

To activate the environment, run the activation script that was created along with the other folders when you set up the virtual environment:

source venv/bin/activate

Installing FastAPI

With the virtual environment activated, we can install the FastAPI library and the Uvicorn ASGI server using the pip package manager:

pip install fastapi uvicorn

Now we can run a test of our application using Uvicorn. The host will be set to localhost on the standard port:

uvicorn main:app --host 127.0.0.1 --port 8000 --reload

Let’s break down this command:

  • --host 127.0.0.1: Specifies the local host IP address.

  • --port 8000: Sets a free port number for TCP/UDP connections, which is not the standard HTTP port 80.

  • main: Refers to the name of the module being run. By default, this is the name of the Python file.

  • app: Refers to the instance of the application created in the code.

  • --reload: Tells Uvicorn to automatically detect changes in the source files and restart the server. This flag should be used only during development.

The default configuration returns a JSON object with the message "Hello World." To verify, you can make a curl request:

curl -X "GET" "http://localhost:8000"

Here, the -X flag is equivalent to the longer --request form and specifies the HTTP request method as GET.

Application Code

Open the main.py file and replace its content with the code for our simple application:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.responses import JSONResponse

app = FastAPI()  # Create an instance of the application

# Root GET request handler with the app.get decorator

@app.get("/")
async def get_root():
	page = "<h1>Hello World!</h1>"  # Server response text
	return HTMLResponse(content=page)

# GET request handler for a simple page request with the app.get decorator

@app.get("/pages/{page_number}")
async def get_page(page_number):
	return JSONResponse({"page_number": page_number})

# GET request handler for a simple user request with the app.get decorator

@app.get("/members/{member_number}")
async def get_member(member_number):
	return JSONResponse({"member_number": member_number})

# POST request handler for a simple user logout request with the app.post decorator

@app.post("/logout/")
async def post_logout(member_number: int):
	return JSONResponse({"member_number": member_number, "status": "OK"})

Note that if you name your application instance differently, the Uvicorn command will also change accordingly. For example, if you name the application perfect_router, the command would look like this:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.responses import JSONResponse

perfect_router = FastAPI()

@perfect_router.get("/")
def path_root():
	page = <h1>Hello World!<1>"
	return HTMLResponse(content=page)

In this case, the server start command would be:

uvicorn main:perfect_router --host 127.0.0.1 --port 8000 --reload

Managing the Application with Systemd

Your FastAPI application should run continuously, handling incoming requests even after a system reboot. To achieve this, we will use the systemd process manager, which is built into Linux. This will make our FastAPI application a background service.

Create a systemd service configuration file:

sudo nano /etc/systemd/system/fastapp.service

The content of this file will be:

[Unit]
Description=WebServer on FastAPI
After=network.target
[Service]
User=USERNAME
Group=USERGROUP
WorkingDirectory=/var/www/fastapp
ExecStart=/var/www/fastapp/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000
Restart=always
[Install]
WantedBy=multi-user.target

Replace the following placeholders:

  • USERNAME: Your system’s username.

  • USERGROUP: The main user group name. If you do not have a specific group, you can omit the Group option.

  • /var/www/fastapp: The path to your FastAPI application.

  • /var/www/fastapp/venv: The path to your virtual environment.

To activate the new configuration file, reload systemd:

sudo systemctl daemon-reload

After this command, systemd will reload all configuration files from the /etc/systemd/system/ directory, making them available for starting and monitoring.

Start the new service using the name specified in the file:

sudo systemctl start fastapp

Note that the service name in the command corresponds to the filename in the systemd directory: fastapp.service.

To check the status of the running application, use:

sudo systemctl status fastapp

To enable the application to start automatically at system boot, run:

sudo systemctl enable fastapp

This command will configure systemd to start the FastAPI service on system startup.

(Optional) Using Supervisor Instead of Systemd

Supervisor is a process management system for Unix-like operating systems, including Linux. It is designed to monitor and manage running applications. Essentially, Supervisor is a more advanced alternative to Systemd, though it is not included in the system by default.

Advantages of Systemd:

  • Built-in: Comes pre-installed with the OS. No additional dependencies are needed.

  • User-Friendly: Easy to use as it can be managed like a system service.

Advantages of Supervisor:

  • User Management: Processes can be managed by any user, not just the root user.

  • Web Interface: Comes with a web-based interface for managing processes.

  • Distribution Compatibility: Works on any Linux distribution.

  • Process Flexibility: Offers more features for process management, such as grouping processes and setting priorities.

Installing Supervisor

To install Supervisor on your system, run the following command:

sudo apt install supervisor

After installation, Supervisor will run in the background and start automatically with the system. However, it is a good practice to ensure that the auto-start feature is enabled. We will use Systemd to enable Supervisor:

sudo systemctl enable supervisor

Then manually start Supervisor:

sudo systemctl start supervisor

Configuring the Application Service

Like with Systemd, we need to create a short configuration file for Supervisor to manage our Uvicorn server. This file will be placed in Supervisor’s configuration directory for service files. As with Systemd, we will name it fastapp:

sudo nano /etc/supervisor/conf.d/fastapp.conf

Here’s what the file should contain:

[program:fastapp]
command=/var/www/fastapp/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000
directory=/var/www/fastapp
user=USERNAME
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/www/fastapp/logs/fasterror.log

Let’s break down this configuration:

  • command: The command to run the Uvicorn application with the necessary flags and parameters.

  • user: The system user under which the application will be managed.

  • autostart: Automatically start the process.

  • autorestart: Automatically restart the process if it fails.

  • redirect_stderr: Redirects standard error output.

  • stdout_logfile: Path to the log file for output (including errors) of the running process. We specified a working directory where a logs folder will be created.

Since we have specified a directory for logs in the configuration file, we need to create it manually:

sudo mkdir /var/www/fastapp/logs/

Running the Application with Supervisor

After adding the new configuration file, Supervisor needs to read the configuration settings, just as Systemd does. Use the following command:

sudo supervisorctl reread

After updating the configuration, restart the Supervisor service to apply the changes:

sudo supervisorctl update

To check the status of the application managed by Supervisor, use the command with the service name specified in the configuration file:

sudo supervisorctl status fastapp

Conclusion

In this brief guide, we demonstrated how to deploy a FastAPI-based website on a remote Unix machine using NGINX and Uvicorn servers along with Systemd for process management.

Optionally, you can use the more advanced tool Supervisor for managing FastAPI web applications.

By following this tutorial, you have learned:

  • How to install Python and its core dependencies.

  • How to install and configure NGINX to forward user requests to the Uvicorn FastAPI handler.

  • How to install FastAPI.

  • How to create a simple Python application using FastAPI routers.

  • How to ensure the continuous operation of a FastAPI application as a background service using Systemd.

  • How to manage your application with a separate Supervisor service.

The application described in this tutorial is a basic example to explain the process of deploying a FastAPI application. In a real-world project, the toolkit might differ slightly, and tools like Kubernetes are often used for automated deployment and continuous integration/continuous deployment (CI/CD) processes.

Python
16.07.2024
Reading time: 11 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us