Nginx is used to route traffic to the Fastapi server.
Editing default configurations that comes with nginx installation.
# Install Python and Nginx in Server sudo apt install -y python3-pip nginx sudo vim /etc/nginx/nginx.conf sudo vim /etc/nginx/sites-enabled/new_file_name
Setup nginx in the new file
server { listen 80; server_name 0.0.0.0; location / { proxy_pass http://127.0.0.1:8000; } } ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log;
Breakdown with multiple processes
server { listen 80; # standard port for HTTP traffic server_name 0.0.0.0; # catch all traffic to this server location /one { # matching URL prefix proxy_pass http://127.0.0.1:8000; # mathching location will be forwarded proxy to this address } location /two { proxy_pass http://127.0.0.1:8001; } }
With HTTPS redirect
server { listen 443 ssl; # standard port for HTTPS traffic server_name 0.0.0.0; # all traffic location / { proxy_pass http://127.0.0.1:8000;
HTTPs setup
server { listen 443 ssl; server_name www.example.com; ssl_certificate www.example.com.crt; ssl_certificate_key www.example.com.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ... }
# Start nginx sudo service nginx restart # Test nginx sudo nginx -t # stop nginx sudo service nginx stop sudo systemctl enable nginx sudo systemctl start nginx sudo systemctl status nginx # FastAPI run # Uvicorn is the server runner pip install uvicorn # Run fastapi using Uvicorn uvicorn file_name:app # Run fastapi in specified port uvicorn main:app --port 8001
# View Nginx Access Log sudo vim /var/log/nginx/access.log # View Nginx Error Log sudo vim /var/log/nginx/error.log
Make output console scrollable
"your_command" | less
# remove nginx sudo apt-get remove nginx nginx-common # remove including configuration files sudo apt-get purge nginx nginx-common