Skip to main content

Tutorial: Setting Up a FastAPI Server with Nginx Reverse Proxy and HTTPS

In this tutorial, I will guide you through setting up a FastAPI server on a remote machine, configuring Nginx as a reverse proxy, and enabling HTTPS using Certbot.

Step 1: Setting Up a Non-sudo User on the Remote Machine

  1. Create a Non-sudo User:

    sudo adduser karthik
    
  2. Switch to the New User:

    su karthik
    
  3. Create SSH Directory and Authorized Keys:

    cd ~/
    mkdir .ssh
    touch .ssh/authorized_keys
    

    Append your local machine's SSH public key to ~/.ssh/authorized_keys on the remote machine.

Step 2: Installing Nginx

  1. Install Nginx:

    sudo apt-get update
    sudo apt-get install nginx
    
  2. Verify Nginx Installation: Open a web browser and enter your remote machine's IP address. You should see the Nginx welcome page.

Step 3: Configuring Nginx as a Reverse Proxy

  1. Edit Nginx Configuration:

    sudo nano /etc/nginx/sites-available/fastapi
    

    Add the following configuration (use a simple webserver for testing this):

    server {
        listen 80;
        server_name your_domain;
    
        location / {
            proxy_pass http://127.0.0.1:8000; # FastAPI server address
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    
  2. Enable the Site:

    sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/
    
  3. Test Nginx Configuration:

    sudo nginx -t
    
  4. Restart Nginx:

    sudo systemctl restart nginx
    

Step 4: Enabling HTTPS with Certbot

Note : You need to create a A type DNS Record from your domain registar pointing to your static public ip address before this step, otherwise certbot will fail to generate certificates.

  1. Install Certbot for Nginx:

    sudo apt-get install python3-certbot-nginx
    
  2. Obtain SSL Certificate:

    sudo certbot certonly --nginx -d your_domain_or_subdomain
    
  3. Update Nginx Configuration for HTTPS: Update /etc/nginx/sites-available/fastapi with HTTPS settings:

    server 
     {
         listen 80;
         listen [::]:80;
         server_name your_domain;
    
         # Redirect all HTTP traffic to HTTPS
         if ($host = $server_name) {
             return 301 https://$host$request_uri;
         }
    
         return 404;
     }
    
     server 
     {
         listen 443 ssl;
         listen [::]:443 ssl;
         server_name your_domain;
    
         ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem;
         ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem;
         include /etc/letsencrypt/options-ssl-nginx.conf;
         ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    
         keepalive_timeout 5;
         client_max_body_size 1G;
    
         location / 
         {
             proxy_pass http://127.0.0.1:8000;
             proxy_set_header Host $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         }
     }
    
  4. Test Nginx Configuration and Restart:

    sudo nginx -t
    sudo systemctl restart nginx
    

Step 5: Deploying FastAPI Server

  1. Install Micromamba and Create Virtual Environment:

    "${SHELL}" <(curl -L micro.mamba.pm/install.sh)
    micromamba create -n myenv python=3.8
    micromamba activate myenv
    
  2. Install Dependencies and Start FastAPI Server:

    pip install fastapi uvicorn gunicorn
    mkdir ~/Projects/myproject
    cd ~/Projects/myproject
    touch main.py
    

    Example main.py:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
  3. Create a Systemd Service for the FastAPI Server: Create /etc/systemd/system/fastapi.service:

    [Unit]
    Description=FastAPI Service
    After=network.target
    
    [Service]
    User=karthik
    Group=karthik
    WorkingDirectory=/home/karthik/Projects/myproject
    ExecStart=/home/karthik/.local/bin/micromamba run -n myenv gunicorn -w 1 -k uvicorn.workers.UvicornWorker main:app -b 127.0.0.1:8000
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    
  4. Enable and Start the Service:

    sudo systemctl daemon-reload
    sudo systemctl enable fastapi.service
    sudo systemctl start fastapi.service
    

Conclusion

You have successfully set up a FastAPI server on a remote machine, configured Nginx as a reverse proxy, and secured it with HTTPS using Certbot. Your FastAPI application is now accessible via your domain over a secure connection.

Feel free to customize your FastAPI application and Nginx configuration further based on your project requirements.


This tutorial provides a comprehensive guide from setting up basic server access to deploying a FastAPI application with Nginx. Happy coding!

Comments

Popular posts from this blog

The Purpose

  The sun was just about to set. I reached just then. I got down from the car and walked to the river. I kneeled down and put my hand in the water. The water in the river had a little warmth because it was a sunny day. I sat down there, waving my hand for some time. It was so good, I hoped the time stopped then and there. Then I thought, my hand was feeling the experience of water. Irrespective of which part of the river I put my hand in, the experience will remain mostly stay the same. If I enter the river and swim, then my experience would become more vivid and significant. If I submerge myself completely underwater then the experience of water around me becomes everything. Hypothetically, just imagine because of my sheer desire to stay there I obtain the ability to breathe and live underwater. I would probably choose to explore further rather than swim back to the surface. I will start imitating any creature I would find living in that water. Slowly I will learn a movement of my own

Unmaking

What helps you survive may also be the one thing that is killing the life in you. What someone desires the most can be just a talk or walk away. But the things that people do to prove that they belong!!!. No one can get a life with absolute freedom and no consequences. But sometimes it's just comforting to imagine what can be and forget what can never be. Becoming an adult presents you with an exciting set of problems. Sometimes a few daunting ones too. Gradually one may either become more desperate or get better at coming to terms with their desperation. Your goals are not any more straight lines, but elaborate mazes. You have to deal with that recurring thoughts of dissatisfaction with the things, and experiences that you desired but didn't pursue. But all of this, all the good, bad, the ugly is what anyone faces. But it's not an end, but rather a new beginning. One has to go through great endeavors, grand failures, and complex circumstances, to understand oneself. And ch

Who am I?

  I'm the shadow behind what is expressible. I'm the core of what can never be expressed. I'm the one inside the darkness. I'm also the one in its absence. I dwell in depths of silence. I'm the ruler of the hall of sounds. I'm the cause behind every intention. I'm the force behind every action. I'm the offering. I'm the receiver of the offering. I'm the one who is called in every chant. I'm the blessing. I'm the one who is bestowing blessing. I'm also the one who is getting the blessing. I'm the water, fire, air, matter, space. I`m the one causing time. I'm the one beyond time. I'm the dream. I'm the one dreaming. I'm also the one free from the dream. I'm an integral part of every form. I'm also formless. I'm the witness. I'm the one being witnessed. There isn't anything, anywhere, anytime that is not me.