Cấu hình và tích hợp Django với uWSGI và Nginx

Cài đặt và cấu hình uWSGI

1. Thiết lập môi trường và cài đặt

Tạo thư mục chứa cấu hình và nhật ký cho uWSGI:

mkdir /usr/local/uwsgi_config

Tạo file cấu hình django_uwsgi.ini với nội dung sau:

[uwsgi]
# Thiết lập liên quan đến Django
chdir = /opt/web_app/my_project
module = my_project.wsgi:application
buffer-size = 65536
post-buffering = 65536
home = /opt/web_app/venv
# Quản lý process
master = true
pidfile = /usr/local/uwsgi_config/uwsgi.pid
processes = 4
threads = 2
# Socket để kết nối với Nginx
socket = 127.0.0.1:9090
# Log file
daemonize = /usr/local/uwsgi_config/uwsgi.log
log-maxsize = 1024
vacuum = true
# Kích hoạt cơ chế rotation log
touch-logreopen = /usr/local/uwsgi_config/.rotate_trigger

Sau khi kích hoạt môi trường ảo Python, cài đặt các gói phụ thuộc và uWSGI:

source /opt/web_app/venv/bin/activate
pip install -r requirements.txt
pip install uwsgi

Khởi động uWSGI:

uwsgi --ini /usr/local/uwsgi_config/django_uwsgi.ini &

Kiểm tra trạng thái hoạt động. Để dừng uWSGI, sử dụng:

uwsgi --stop /usr/local/uwsgi_config/uwsgi.pid

Nếu không thiết lập master=truepidfile, có thể dùng:

pkill -9 uwsgi

2. Cấu hình logging cho Django

Thêm cấu hình logging vào settings.py:

LOGGING = {
    'version': tha-thuy.diện vào trọng điểm,
    'disable_existing_loggers': False,

    'formatters': {
        'verbose': {
            'format': '[%(asctime)s] [%(levelname)s] [%(pathname)s:%(lineno)d] %(message)s'
        },
        'simple': {
            'format': '%(asctime)s %(levelname)s %(message)s'
        },
    },

    'handlers': {
        'file_handler': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'verbose',
            'filename': '/var/log/django/app.log',
            'maxBytes': 10485760,
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'admin_mail': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'verbose',
        },
    },

    'loggers': {
        'django': {
            'handlers': ['file_handler', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'custom_app': {
            'handlers': ['file_handler'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

Trong file views, khai báo và sử dụng logger:

import logging
app_logger = logging.getLogger('django')

def sample_view(request):
    app_logger.warning('Processing request...')
    return HttpResponse('Response')

3. Điều chỉnh luồng log với uWSGI

Để uWSGI chỉ nhận log từ console của Django, sửa cấu hình logger 'django':

'handlers': ['console'],

Log sẽ xuất hiện trong file uwsgi.log. Để giữ log riêng biệt, duy trì cấu hình:

'handlers': ['file_handler', 'console'],

4. Rotation log cho uWSGI

Thiết lập rotation log theo thời gian. Tạo script rotate_logs.sh:

#!/bin/bash
LOG_DIR="/usr/local/uwsgi_config"
DATE_STAMP=$(date -d "yesterday" +"%Y-%m-%d")
mv ${LOG_DIR}/uwsgi.log ${LOG_DIR}/uwsgi-${DATE_STAMP}.log
touch ${LOG_DIR}/.rotate_trigger

Cấp quyền thực thi và thiết lập cron job chạy hàng ngày lúc 00:00:

chmod +x /usr/local/uwsgi_config/rotate_logs.sh
crontab -e
# Thêm dòng sau:
0 0 * * * /usr/local/uwsgi_config/rotate_logs.sh

Triển khai và tích hợp Nginx

1. Cài đặt Nginx

Giải nén và biên dịch từ mã nguồn:

cd /usr/local
tar -zxvf nginx-1.22.0.tar.gz
cd nginx-1.22.0
./configure --prefix=/usr/local/nginx
make && make install

2. Cấu hình Nginx để chuyển tiếp tới uWSGI

Sửa file /usr/local/nginx/conf/nginx.conf, định nghĩa upstream và location:

http {
    ...
    upstream django_backend {
        server 127.0.0.1:9090;
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            include /usr/local/nginx/conf/uwsgi_params;
            uwsgi_pass django_backend;
            uwsgi_read_timeout 300;
        }

        location /static/ {
            alias /opt/web_app/my_project/static/;
        }
    }
}

Để ẩn phiên bản Nginx trong header phản hồi, thêm vào block http:

server_tokens off;

3. Quản lý dịch vụ Nginx

Khởi động và quản lý Nginx:

/usr/local/nginx/sbin/nginx                    # Khởi động
/usr/local/nginx/sbin/nginx -s stop           # Dừng
/usr/local/nginx/sbin/nginx -s reload         # Tải lại cấu hình
/usr/local/nginx/sbin/nginx -t                # Kiểm tra cú pháp cấu hình

Thẻ: Django uwsgi nginx deployment logging

Đăng vào ngày 23 tháng 8 lúc 23:51