🚀 Deploying a Flask Backend on a Server (VPC)

Learn how to set up a Flask backend with Nginx and systemd for seamless deployment.

1️⃣ Setting Up the Server

Ensure you have SSH access and install dependencies.

ssh user@your-server-ip
    sudo apt update && sudo apt upgrade -y
    sudo apt install python3 python3-pip python3-venv nginx -y

2️⃣ Deploying the Flask Application

Create a project directory and set up a virtual environment.

mkdir ~/flask_app && cd ~/flask_app
    python3 -m venv venv
    source venv/bin/activate
    pip install flask gunicorn

Create a simple Flask app:

nano app.py
from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return "Hello, Flask on VPC!"
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)

3️⃣ Running Flask with Gunicorn

gunicorn --bind 0.0.0.0:5000 app:app

4️⃣ Configuring Nginx as a Reverse Proxy

Edit the Nginx configuration file:

sudo nano /etc/nginx/sites-available/flask_app
server {
        listen 80;
        server_name your-domain.com;
        location / {
            proxy_pass http://127.0.0.1:5000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

Enable the configuration and restart Nginx:

sudo ln -s /etc/nginx/sites-available/flask_app /etc/nginx/sites-enabled
    sudo systemctl restart nginx

5️⃣ Setting Up Systemd for Gunicorn

sudo nano /etc/systemd/system/flask_app.service
[Unit]
    Description=Gunicorn instance to serve Flask App
    After=network.target
    
    [Service]
    User=user
    Group=www-data
    WorkingDirectory=/home/user/flask_app
    ExecStart=/home/user/flask_app/venv/bin/gunicorn --workers 3 --bind unix:flask_app.sock -m 007 app:app
    
    [Install]
    WantedBy=multi-user.target

Enable and start the service:

sudo systemctl daemon-reload
    sudo systemctl enable flask_app
    sudo systemctl start flask_app

🎯 Final Testing

Visit http://your-server-ip/ in your browser.

Check the logs if needed:

sudo journalctl -u flask_app --no-pager | tail -n 20