![見出し画像](https://assets.st-note.com/production/uploads/images/59528705/rectangle_large_type_2_ea01c20e6142f25cf494b72145721a4e.png?width=800)
Django 入門 (6) - Nginx
「Django」での「Nginx」の使い方をまとめました。
・Django 3.0.8
前回
1. Nginx
「Nginx」(エンジンエックス)はWebサーバーアプリです。「Django」で作成したWebフレームワークアプリを公開する時には、このWebサーバーアプリが必要になります。
2. WSGI
「WSGI」は、WebフレームワークアプリとWebサーバーアプリを繋ぐインタフェースです。これによって、様々なWebフレームワークアプリとWebサーバーアプリを組み合わせて利用できるようになっています。
主なWebフレームワークアプリは、次のとおりです。
・Django
・Bottle
・Flask
・Tornado
・web2Py
主なWebサーバーアプリは、次のとおりです。
・Nginx
・Apache
3. Nginxのインストール
「Nginx」のインストールの手順は、次のとおりです。
(1) 以下のコマンドで、Nginxをインストール。
macOSでのインストール方法になります。
$ brew install nginx
(2) 以下のコマンドで、Nginxサーバーの起動。
$ nginx
(3) ブラウザで「http://localhost:8080 」を開く。
(4) 以下のコマンドで、Nginxサーバーの停止。
$ nginx -s stop
5. uWSGIでのWebページの表示
「uWSGI」経由でWebアプリ(hello)を実行してみます。「Django 入門 (2) - アプリの追加」で作ったアプリになります。
【WEBブラウザ】 → 【uWSGI】 → 【Webアプリ】
(1) 「uWSGI」のインストール。
「uWSGI」はWSGIのPythonパッケージです。
$ pip install uwsgi
(2) 以下のコマンドで、Webアプリを「uWSGI」で実行してみます。
引数には、「hello_app/hello_app/wsgi.py」を指定しています。
$ uwsgi --http :8000 --module hello_app.wsgi
(3) ブラウザで「http://localhost:8000/hello」を開く。
「Django」と「uWSGI」を繋ぐことができました。
6. Nginx経由でのWebアプリの実行
「Nginx」と「uWSGI」経由でWebアプリ(hello)を実行してみます。
【WEBブラウザ】 → 【Nginx】 → 【uWSGI】 → 【Webアプリ】
(1) 「hello_app/uwsgi_params」を作成し、以下のように編集。
「uWSGI」の設定ファイルになります。
uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;
(2) 「hello_app/hello_app/settings.py」の末尾に、以下の設定を追加。
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
(3) プロジェクト直下(hello_app/static)にstaticフォルダを生成。
$ python manage.py collectstatic
(4) 「hello_app/hello_nginx.conf」を作成し、以下のように編集。
「Nginx」の設定ファイルになります。staticとuwsgi_paramsのパスを環境に合わせて指定します。
upstream django {
server 127.0.0.1:8001;
}
server {
listen 8000;
server_name 127.0.0.1;
charset utf-8;
location /static {
alias /Users/username/work/hello_app/hello/static;
}
location / {
uwsgi_pass django;
include /Users/username/work/hello_app/uwsgi_params;
}
}
(5) シンボリックリンクを/usr/local/etc/nginx/sites-enabled/に貼る。
「Nginx」が「hello_nginx.conf」を参照できる場所に配置します。
$ mkdir /usr/local/etc/nginx/sites-enabled/
$ sudo ln -s /Users/username/work/hello_app/hello_nginx.conf /usr/local/etc/nginx/sites-enabled/
(6) 「/usr/local/etc/nginx/sites-nginx.conf」の末尾近くに、以下の設定を追加。
「hello_nginx.conf」を追加しています。
include /usr/local/etc/nginx/sites-enabled/*.conf;
include servers/*;
}
(7) 「Nginx」を実行。実行中の場合は、リロード。
$ nginx
$ nginx -s reload
(8) 「uWSGI」を実行。
$ uwsgi --socket :8001 --module hello_app.wsgi
(9) ブラウザで「http://localhost:8000/hello」を開く。
「Django」と「Nginx」を繋ぐことができました。
この記事が気に入ったらサポートをしてみませんか?