How to deploy a Python app on a VPS

How to deploy a Python app on a VPS - Part I

December 16, 2024

Image created by Midjourney


There's a lot of debate these days about avoiding serverless platforms for deploying your applications. I personally like to have some control over my resources and applications, but whatever camp you belong in, I think learning how to manage a server and host your apps in it is a timeless skill, especially if you're a backend engineer.

My go-to strategy to deploy a web app is through a VPS. I use DigitalOcean droplets as my choice of VPS, but you can use whatever you want. The process should be more or less the same. This post is part of series where I'll show you how to deploy a Flask web app on a cheap VPS. I'm not going to show you how to spin up a DigitalOcean droplet because there are plenty of tutorials to teach you that. Once you have a droplet set up and have successfully SSH'd into it, you can start this tutorial


Add sudo users

You'll need to add a sudo user to do sysadmin stuff. You can name it whatever you want. I'm gonna use a variable called new_user that you can initialize before copying these commands. I'll set it to prithaj in this example

  
    new_user=prithaj
  

Now create a new user and add them to the sudo group

  
    adduser $new_user
    usermod -aG sudo $new_user
  

Copy root SSH config to new users

This will let you SSH into the droplet as your own user and not root

  
    mkdir /home/$new_user/.ssh
    cp /root/.ssh/authorized_keys /home/$new_user/.ssh/authorized_keys
    chown $new_user.$new_user /home/$new_user/.ssh/authorized_keys
  

Disable root SSH access

For security reasons, it's probably a good idea to disable root SSH access. WARNING: Before copying these commands please make sure 1. You can SSH into your droplet as your own user 2. You can run sudo commands

  
  ssh root@$DROPLET_IP
  rm ~/.ssh/authorized_keys
  exit
  

If you try to ssh into the droplet now as root if should fail with a permission denied error

   
  ssh root@$DROPLET_IP
  

Install packages

Now it's time to install some packages. We're gonna be using Docker to containerize the app and GitHub Actions to set up our CI/CD pipeline. Before installing anything lets' make sure everything is up to date

   
  sudo apt update 
  sudo apt upgrade
  

In the next post I cover how to set up Docker and GitHub Actions