Introduction

Flask is a micro web framework written in Python. Gunicorn is a WSGI HTTP server for running Python web applications. Nginx is a web server that can also be used as a reverse proxy. This guide will walk you through the process of installing Flask with Gunicorn and setting up Nginx as a reverse proxy on Debian 12.

Prerequisites

Before you begin, ensure you have:

  1. A Debian 12 server or desktop system
  2. Root or sudo privileges

Step 1: Install Flask and Gunicorn

Open a terminal and install Flask and Gunicorn using pip:

sudo apt update
sudo apt install -y python3-pip
pip3 install Flask gunicorn

Step 2: Create a Flask Application

Create a new directory for your Flask application:

mkdir ~/my_flask_app
cd ~/my_flask_app

Create a Python file for your Flask application, e.g., app.py:

nano app.py

Add the following code to app.py to create a simple Flask application:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, Flask!"

if __name__ == '__main__':
    app.run(debug=True)

Save and close the file.

Step 3: Run the Flask Application with Gunicorn

Run the Flask application with Gunicorn by running the following command in the terminal:

gunicorn -w 4 -b 127.0.0.1:8000 app:app

This will start the Flask application using Gunicorn on port 8000.

Step 4: Install and Configure Nginx

Install Nginx:

sudo apt install -y nginx

Create a new Nginx server block configuration file:

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

Add the following configuration to the file:

server {
    listen 80;
    server_name your_domain.com;

    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;
    }
}

Enable the Nginx server block and restart Nginx:

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

Step 5: Access Your Flask Application

In your web browser, navigate to your server's domain name or IP address. You should see your Flask application running via Nginx.

Conclusion

Congratulations! You have successfully installed Flask with Gunicorn and set up Nginx as a reverse proxy on Debian 12. You can now deploy and run Flask applications using Gunicorn and serve them with Nginx.

Was this answer helpful? 0 Users Found This Useful (0 Votes)