Ana içeriğe geç
Kategoriye Dön

Python/Django Deploy: Gunicorn ve Nginx ile Üretim

Python/Django uygulamasını VPS'e deploy etme rehberi. Virtualenv kurulumu, Django üretim ayarları, Gunicorn WSGI sunucusu, Nginx reverse proxy, systemd servisi ve statik dosya yönetimi.

Okuma süresi: 18 dk Web Hosting / Uygulama
pythondjangogunicornnginxdeployvpsvirtualenvwsgipostgresql

İçindekiler

Python/Django Deploy: Gunicorn ve Nginx ile Üretim Ortamı

Django, Python'un en popüler web framework'üdür. Üretim ortamına deploy etmek için Gunicorn (WSGI sunucusu) ve Nginx (reverse proxy) kombinasyonu endüstri standardıdır. Bu rehberde sıfırdan Django uygulamanızı VPS'e deploy etmeyi öğreneceksiniz.

Python ve Virtualenv Kurulumu

hljs bash
# Sistem güncellemesi
sudo apt update && sudo apt upgrade -y

# Python 3 ve pip kur
sudo apt install python3 python3-pip python3-venv python3-dev -y

# Python sürümünü kontrol et
python3 --version
pip3 --version

# Uygulama dizini oluştur
sudo mkdir -p /var/www/mydjango
sudo chown $USER:$USER /var/www/mydjango
cd /var/www/mydjango

# Virtual environment oluştur
python3 -m venv venv

# Virtual environment'ı aktifleştir
source venv/bin/activate

# pip'i güncelle
pip install --upgrade pip

Her Django projesi için ayrı bir virtual environment kullanın. Bu, bağımlılık çakışmalarını önler ve projeleri izole eder.

Uygulamayı Sunucuya Aktarma

hljs bash
# Repoyu klonla
cd /var/www
git clone https://github.com/kullanici/mydjango.git
cd mydjango

# Virtual environment oluştur ve aktifleştir
python3 -m venv venv
source venv/bin/activate

# Bağımlılıkları kur
pip install -r requirements.txt

# Gunicorn kur
pip install gunicorn

Django Üretim Ayarları

hljs bash
# .env dosyası oluştur
nano /var/www/mydjango/.env
hljs env
DJANGO_SECRET_KEY=cok-gizli-ve-uzun-bir-anahtar-buraya
DJANGO_DEBUG=False
DJANGO_ALLOWED_HOSTS=example.com,www.example.com
DATABASE_URL=postgresql://dbuser:dbpass@localhost:5432/mydb
REDIS_URL=redis://localhost:6379/0
hljs python
# settings/production.py veya settings.py içinde
import os
from pathlib import Path

# Güvenlik
DEBUG = False
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', '').split(',')

# Güvenlik başlıkları
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# Statik dosyalar
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '/var/log/django/error.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

Veritabanı Kurulumu (PostgreSQL)

hljs bash
# PostgreSQL kur
sudo apt install postgresql postgresql-contrib -y

# PostgreSQL'e bağlan
sudo -u postgres psql
hljs sql
CREATE DATABASE mydb;
CREATE USER dbuser WITH PASSWORD 'guclu-sifre';
ALTER ROLE dbuser SET client_encoding TO 'utf8';
ALTER ROLE dbuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE dbuser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE mydb TO dbuser;
\q
hljs bash
# psycopg2 kur
pip install psycopg2-binary

# Migration çalıştır
python manage.py migrate

# Superuser oluştur
python manage.py createsuperuser

# Statik dosyaları topla
python manage.py collectstatic --noinput

Gunicorn Yapılandırması

hljs bash
# Gunicorn'u test et
cd /var/www/mydjango
source venv/bin/activate
gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application

# Gunicorn yapılandırma dosyası
nano /var/www/mydjango/gunicorn.conf.py
hljs python
# gunicorn.conf.py
bind = 'unix:/run/gunicorn/gunicorn.sock'
workers = 3  # (2 * CPU çekirdeği) + 1
worker_class = 'sync'
worker_connections = 1000
timeout = 30
keepalive = 2
max_requests = 1000
max_requests_jitter = 50
preload_app = True
user = 'www-data'
group = 'www-data'
errorlog = '/var/log/gunicorn/error.log'
accesslog = '/var/log/gunicorn/access.log'
loglevel = 'info'

Systemd Servis Dosyası

hljs bash
# Log dizinleri oluştur
sudo mkdir -p /var/log/gunicorn /run/gunicorn
sudo chown www-data:www-data /var/log/gunicorn /run/gunicorn

# Systemd servis dosyası oluştur
sudo nano /etc/systemd/system/gunicorn.service
hljs ini
[Unit]
Description=Gunicorn daemon for Django
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/mydjango
ExecStart=/var/www/mydjango/venv/bin/gunicorn \
    --config /var/www/mydjango/gunicorn.conf.py \
    myproject.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
EnvironmentFile=/var/www/mydjango/.env

[Install]
WantedBy=multi-user.target
hljs bash
# Servisi etkinleştir ve başlat
sudo systemctl daemon-reload
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
sudo systemctl status gunicorn

Nginx Reverse Proxy Yapılandırması

hljs bash
sudo nano /etc/nginx/sites-available/mydjango
hljs nginx
server {
    listen 80;
    server_name example.com www.example.com;

    # Statik dosyalar
    location /static/ {
        alias /var/www/mydjango/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Medya dosyaları
    location /media/ {
        alias /var/www/mydjango/media/;
    }

    # Gunicorn'a proxy
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn/gunicorn.sock;
        proxy_read_timeout 300;
        proxy_connect_timeout 300;
    }

    client_max_body_size 100M;
    access_log /var/log/nginx/mydjango.access.log;
    error_log /var/log/nginx/mydjango.error.log;
}
hljs bash
sudo ln -s /etc/nginx/sites-available/mydjango /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

SSL Sertifikası

hljs bash
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Deployment Workflow

hljs bash
# Güncellemeleri deploy et
cd /var/www/mydjango
source venv/bin/activate
git pull origin main
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl restart gunicorn

REXE sunucularında Django için en az 1 GB RAM önerilir. Gunicorn worker sayısını CPU çekirdeği sayısına göre ayarlayın: (2 × CPU) + 1.

Sonuç

Django uygulamanız artık Gunicorn WSGI sunucusu ve Nginx reverse proxy ile üretim ortamında çalışıyor. Systemd servisi sayesinde sunucu yeniden başladığında uygulama otomatik olarak başlar.