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

Sin

I wonder... If one performs good deeds, are their actions rewarded?. And is it a sin to just have good intentions but never be able to act upon them ?. Are evil deeds punished?. If yes, who is the one? who is going to punish or reward?. Or it's just going to be a subtle soup of one's own disappointment or satisfaction about their actions after one's death?. Floating around and waiting to either be reborn of disappointment or escape the cycle of birth and death just by mere satisfaction of their actions?. Well someone may tell me that it may depend on whether they feel regretful or content. Otherwise, how could one either be disappointed or satisfied. Well, I don't know for sure. Thinking about all this, I find the sin a tad bit fascinating. If one does sin and if it does not affect any other being or environment, even at a subtle level, then I find it hard to call it a sin anymore. Well if someone may feel regret, even if it's objectively a good thing to do, then is...

Hence You Are Curious - Intro

  నిజమో కాదో తెలియని ప్రలోభనాలను వద్దనవే ! In the beginning, there was an infinite cosmic ocean engulfed by darkness. And then, there was the seed. What was that seed ?. It could be the desire, the desire to manifest. It could be the word, the vibration leading to the emergence of consciousness. It is what seers experienced when they dwelled deep within their hearts. And hence, the one before anything projected itself into all this. This is a state of neither real nor unreal. There is the truth in and beyond all this, Something only the realized ones seem to comprehend. The power of intention of the one before anything has led to the possibility of creation. And the power to act ignited the process of creation. Embedded power of knowledge holding everything. That one seed spiraled into never-ending ripples making the universe, holding the power within itself to sustain, make, and unmake itself.  Various seers have experienced different realizations upon meditating. For one, it...