You have your Python app running on a WSGI server (like Waitress or Gunicorn), but you aren’t ready to launch yet. Exposing a WSGI server directly to the internet is a security risk and inefficient for handling static files.
You need Nginx.
Nginx acts as a Reverse Proxy. It sits in front of your application, accepting traffic from the internet (on port 80) and forwarding it to your Python app (on port 8080). This architecture improves security, load balancing, and speed.
Prerequisites
-
A server running Linux (Ubuntu/Debian).
-
A Python app running on
localhost:8080.
Step 1: Install Nginx
Update your package manager and install Nginx:
-
Ubuntu/Debian:
sudo apt update sudo apt install nginx -
RHEL/CentOS/AlmaLinux:
sudo dnf install nginx sudo systemctl enable --now nginx
Step 2: Create the Configuration File
Important: RHEL and Ubuntu organize config files differently.
Option A: Ubuntu/Debian (Sites-Available method) Ubuntu uses the sites-available and sites-enabled directory structure.
-
Create file:
sudo nano /etc/nginx/sites-available/my_app -
Paste config.
-
Link file:
sudo ln -s /etc/nginx/sites-available/my_app /etc/nginx/sites-enabled/
Option B: RHEL/CentOS/AlmaLinux (Conf.d method) RHEL simply loads any .conf file inside the conf.d directory.
-
Create file:
sudo nano /etc/nginx/conf.d/my_app.conf -
Paste the configuration below directly into this file. No linking is required.
Step 3: The Nginx Configuration Block
Use this block for both operating systems:
server {
listen 80;
server_name example.com www.example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Step 4: [Critical for RHEL] Configure SELinux & Firewall
On RHEL-based systems, SELinux will block Nginx from talking to your Python app by default, resulting in a “502 Bad Gateway” error.
-
Allow Nginx to make network connections:
sudo setsebool -P httpd_can_network_connect 1 -
Open HTTP ports in the firewall:
sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --reload
Step 5: Test and Restart
sudo nginx -t
sudo systemctl restart nginx
Conclusion
Navigate to your domain or IP address in your browser. You should see your Python application running!
However, look at the address bar. It says “Not Secure.” In the next guide, we will fix that by installing a free SSL certificate.
