How to Set Up Python with Gunicorn and Nginx
How to Set Up Python with Gunicorn and Nginx
Install Python
apt update
apt install python3 python3-pip python3-venv -y
mkdir /var/www/myapp && cd /var/www/myapp
python3 -m venv venv
source venv/bin/activate
pip install flask gunicorn
Create a Systemd Service for Gunicorn
Create /etc/systemd/system/myapp.service:
[Unit]
Description=My Python App
After=network.target
[Service]
User=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/var/www/myapp/venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 app:app
Restart=always
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start myapp
systemctl enable myapp
Configure Nginx as Reverse Proxy
Add to your Nginx site config:
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;
proxy_set_header X-Forwarded-Proto $scheme;
}
systemctl reload nginx