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

كيفية نشر Flask باستخدام Gunicorn وNginx على Ubuntu VPS: الدليل الكامل لعام 2026

⏱️4 min read  ·  810 words

خادم التطوير المدمج في Flask ليس مناسبًا للإنتاج — فهو ذو ترابط واحد، ولا يحتوي على إدارة للعمليات، ويكشف عن آثار بايثون الأولية. يستخدم نشر قارورة الإنتاججونيكورن كخادم تطبيق WSGI ونجينكس كالوكيل العكسي. يغطي هذا الدليل الإعداد الكامل على 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

نقطة إدخال تطبيق Flask (app.py or wsgi.py):

# wsgi.py
from myapp import create_app

app = create_app()

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

الخطوة 3: تكوين Gunicorn

# /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: خدمة systemd

# /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: تكوين Nginx

# /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: SSL مع Let’s Encrypt

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

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

يقوم Certbot تلقائيًا بتعديل تكوين Nginx لإضافة SSL، وإعادة توجيه HTTP إلى HTTPS، وإضافة مهمة cron لتجديد الشهادة.

الخطوة 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

Environment Variables (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 يعالج هذا الإعداد ما يلي: العمليات المنفذة المتعددة للتزامن، وعمليات إعادة التحميل بدون توقف، وإنهاء SSL، وتحسين الملفات الثابتة، وإعادة التشغيل التلقائي للعملية عند الفشل. إنه كل ما تحتاجه لخدمة تطبيق Flask الإنتاجي بشكل موثوق.

✍️ Leave a Comment

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

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