🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

उबंटू वीपीएस पर गुनिकॉर्न और नेग्नेक्स के साथ फ्लास्क कैसे तैनात करें: संपूर्ण 2026 गाइड

⏱️4 min read  ·  809 words

फ्लास्क का अंतर्निर्मित विकास सर्वर उत्पादन के लिए उपयुक्त नहीं है – यह एकल-थ्रेडेड है, इसमें कोई प्रक्रिया प्रबंधन नहीं है, और कच्चे पायथन ट्रेसबैक को उजागर करता है। एक उत्पादन फ्लास्क परिनियोजनका उपयोग करता है गुनिकॉर्न डब्लूएसजीआई एप्लिकेशन सर्वर औरके रूप में Nginx रिवर्स प्रॉक्सी के रूप में। यह मार्गदर्शिका Ubuntu 22.04 पर संपूर्ण सेटअप को कवर करती है।

वास्तुकला अवलोकन

Internet → Nginx (port 80/443, SSL termination, static files)
               ↓
          Gunicorn (port 8000, multiple worker processes)
               ↓
          Flask Application (WSGI app)

चरण 1: सर्वर सेटअप

sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-pip python3-venv nginx certbot python3-certbot-nginx

# Create application user (don't run as root)
sudo useradd -m -s /bin/bash flaskapp
sudo mkdir /var/www/myapp
sudo chown flaskapp:flaskapp /var/www/myapp

चरण 2: एप्लिकेशन परिनियोजित करें

sudo su - flaskapp
cd /var/www/myapp

# Clone your repo
git clone https://github.com/youruser/myapp.git .

# Create virtual environment
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicorn

आपका फ्लास्क ऐप प्रवेश बिंदु (app.py or wsgi.py):

# wsgi.py
from myapp import create_app

app = create_app()

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

चरण 3: गुनिकॉर्न कॉन्फ़िगर करें

# /var/www/myapp/gunicorn.conf.py
bind              = "127.0.0.1:8000"
workers           = 4          # rule: (2 × CPU cores) + 1
worker_class      = "gthread"  # threaded worker for I/O-bound apps
threads           = 2
timeout           = 120
keepalive         = 5
max_requests      = 1000       # restart worker after N requests (prevents memory leaks)
max_requests_jitter = 50       # randomize restart to avoid thundering herd
errorlog          = "/var/log/gunicorn/error.log"
accesslog         = "/var/log/gunicorn/access.log"
loglevel          = "info"
preload_app       = True       # load app before forking workers (faster startup)
sudo mkdir /var/log/gunicorn
sudo chown flaskapp:flaskapp /var/log/gunicorn

# Test gunicorn starts correctly
cd /var/www/myapp
source venv/bin/activate
gunicorn --config gunicorn.conf.py wsgi:app

चरण 4: सिस्टमडी सर्विस

# /etc/systemd/system/myapp.service
[Unit]
Description=Gunicorn daemon for myapp
After=network.target

[Service]
User=flaskapp
Group=flaskapp
WorkingDirectory=/var/www/myapp
Environment="PATH=/var/www/myapp/venv/bin"
EnvironmentFile=/var/www/myapp/.env
ExecStart=/var/www/myapp/venv/bin/gunicorn           --config gunicorn.conf.py           wsgi:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp   # start on boot
sudo systemctl status myapp   # verify running

चरण 5: नेग्नेक्स कॉन्फ़िगरेशन

# /etc/nginx/sites-available/myapp
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    # Static files served directly by Nginx (much faster than Gunicorn)
    location /static {
        alias /var/www/myapp/static;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Proxy everything else to Gunicorn
    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;
        proxy_read_timeout 120s;
        proxy_connect_timeout 10s;

        # Security headers
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-Content-Type-Options "nosniff";
        add_header Referrer-Policy "strict-origin-when-cross-origin";
    }

    # Upload size limit
    client_max_body_size 16M;
}
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

चरण 6: लेट्स एनक्रिप्ट के साथ एसएसएल

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

# Verify auto-renewal
sudo certbot renew --dry-run

सर्टिबोट स्वचालित रूप से एसएसएल जोड़ने के लिए आपके नेगनेक्स कॉन्फिगरेशन को संशोधित करता है, HTTP को HTTPS पर रीडायरेक्ट करता है, और प्रमाणपत्र नवीनीकरण के लिए क्रॉन जॉब जोड़ता है।

चरण 7: परिनियोजन वर्कफ़्लो

# After code changes:
cd /var/www/myapp
git pull origin main
source venv/bin/activate
pip install -r requirements.txt  # if dependencies changed
flask db upgrade                  # if migrations exist

# Zero-downtime reload (sends SIGHUP to Gunicorn master)
sudo systemctl reload myapp

# Full restart (brief downtime)
sudo systemctl restart myapp

पर्यावरण चर (Production)

# /var/www/myapp/.env (permissions: 600, owned by flaskapp)
FLASK_ENV=production
SECRET_KEY=your-long-random-secret-key
DATABASE_URL=postgresql://user:pass@localhost/mydb
REDIS_URL=redis://localhost:6379/0
sudo chmod 600 /var/www/myapp/.env
sudo chown flaskapp:flaskapp /var/www/myapp/.env

Monitoring and Logs

# View logs
sudo journalctl -u myapp -f          # systemd logs
sudo tail -f /var/log/gunicorn/error.log
sudo tail -f /var/log/nginx/access.log

# Check worker processes
sudo systemctl status myapp
pgrep -a gunicorn

Frequently Asked Questions

Q: How many Gunicorn workers should I use?
A: (2 × CPU cores) + 1 is the standard formula. For a 2-core VPS: 5 workers. More workers = more memory usage. Use gthread worker class with 2-4 threads for I/O-bound Flask apps.

Q: Gunicorn vs uWSGI?
A: Gunicorn for simplicity and Python ecosystem familiarity. uWSGI is faster but more complex to configure. For most Flask applications, Gunicorn performs identically and is far simpler to set up and maintain.

Q: Why not just run Flask directly on port 80?
A: Nginx handles SSL termination, static file serving (much faster), connection queueing, load balancing, security headers, and request buffering. Running Flask directly means one process per connection, no SSL optimization, and slow static file serving.

Q: How do I handle zero-downtime deploys?
A: systemctl reload myapp sends SIGHUP to Gunicorn master, which gracefully replaces workers with new ones while finishing in-flight requests. New code loads in new workers without dropping connections.

Q: Should I use Docker instead?
A: Docker is excellent for multi-service apps (with Docker Compose) and for consistency across environments. For a single Flask app on a VPS, systemd + Gunicorn + Nginx is simpler, uses less memory, and is easier to debug. Both approaches work well.

Conclusion

The Flask production stack of Gunicorn + Nginx + systemd is battle-tested, well-documented, and appropriate for applications serving thousands of requests per minute on modest VPS hardware. This setup handles: multiple worker processes for concurrency, graceful zero-downtime पुनः लोड करना, एसएसएल समाप्ति, स्थैतिक फ़ाइल अनुकूलन, और विफलता पर प्रक्रिया ऑटो-रीस्टार्ट यह वह सब कुछ है जो आपको एक उत्पादन फ्लास्क एप्लिकेशन को विश्वसनीय रूप से सेवा प्रदान करने के लिए आवश्यक है।

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা