Djangoアプリケーションの負荷分散をNginxとuWSGIで実装する方法

システム構成

Nginxロードバランサー: 192.168.110.128

uWSGIアプリケーションサーバー: 192.168.110.129, 192.168.110.130, 192.168.110.131

環境設定

Django環境の構築(全uWSGIサーバー)

# システムパッケージのインストール
yum install -y gcc-c++ vim python3 python3-pip

# 仮想環境ツールのインストール
pip3 install virtualenv virtualenvwrapper

# 仮想環境設定
echo 'export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3' >> ~/.bashrc
echo 'export WORKON_HOME=$HOME/.virtualenvs' >> ~/.bashrc
echo 'source /usr/local/bin/virtualenvwrapper.sh' >> ~/.bashrc
source ~/.bashrc

# 仮想環境の作成と有効化
mkvirtualenv django_app
workon django_app

# 依存パッケージのインストール
pip install -r requirements.txt

# uWSGIのインストール
yum install -y python3-devel
pip install uwsgi

# 静的ファイルの収集
python manage.py collectstatic

# ファイアウォールの無効化
systemctl stop firewalld

uWSGI設定ファイル(全アプリケーションサーバー)

[uwsgi]
# Nginx連携用ソケット設定
socket = 0.0.0.0:8082

# プロジェクトディレクトリ
chdir = /home/app_project

# WSGIファイルの指定
module = app_project.wsgi:application

# プロセスとスレッドの設定
processes = 8
threads = 16

# バッファサイズ
buffer-size = 65536

# マスタープロセスとデーモンモード
master = true
daemonize = /var/log/uwsgi/app.log

# 仮想環境の指定
virtualenv = /root/.virtualenvs/django_app

# PIDファイル
pidfile = /tmp/uwsgi.pid

Nginx設定ファイル(ロードバランサー)

worker_processes 8;
worker_rlimit_nofile 65535;

events {
    worker_connections 65535;
    use epoll;
    multi_accept on;
}

http {
    include mime.types;
    default_type application/octet-stream;
    
    sendfile on;
    keepalive_timeout 65;

    # アップストリームサーバーの定義
    upstream django_cluster {
        server 192.168.110.129:8082;
        server 192.168.110.130:8082;
        server 192.168.110.131:8082;
    }

    server {
        listen 8080;
        server_name localhost;

        location / {
            include uwsgi_params;
            uwsgi_pass django_cluster;
        }

        location /static {
            alias /var/www/app/static;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root html;
        }
    }
}

タグ: Django uWSGI nginx 負荷分散 Python

9月26日 09:32 投稿