LoginSignup
0
2

More than 1 year has passed since last update.

Djangoスタートアップ その11(Webアプリ三層構造構築編)

Last updated at Posted at 2023-04-21

作成するWebアプリの構造

ApplicationModel.png

Nginx

Webサーバー。静的コンテンツ(サーバー上のファイル)を高速に配信するように設計されている

gunicorn

WSGIサーバー

wsgi(Web Server Gateway Interface)

WebサーバーとWebアプリケーションを接続するためのインターフェース。webサーバー(Nginx, apache, cgiなど)とPython製のWebアプリケーション(Django, Flask, Zopeなど)の組み合わせの制限を吸収する役目であったり、Webアプリケーションの速度向上を担う。

PostgreSQL

リレーショナルデータベースサーバー。大規模なデータベースを扱うときに便利

gunicornの設定&起動

  • 仮想環境の起動
  • gunicornがインストールされているか確認
which gunicorn

gunicornを起動(プロジェクトディレクトリをカレントにする)

gunicorn --bind 0.0.0.0:8000 (wsgi.pyが入っているディレクトリ名).wsgi

自動起動設定

OS起動時に自動的にgunicornが立ち上がる設定をする。

方法

サービスファイルgunicorn.serviceを記述して、systemdで常時起動させる

/etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/(プロジェクトディレクトリ)
ExecStart=/home/ubuntu/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/(プロジェクトディレクトリ)/(プロジェクトディレクトリ).sock (プロジェクトのwsgi.pyがあるディレクトリ名).wsgi:application

[Install]
WantedBy=multi-user.target

gunicornを起動

sudo systemctl start gunicorn
sudo systemctl enable gunicorn

❓ シンボリックリンクが張られるメリットは?
A. /etc/いかに設定ファイルを置くと、アプリケーションとは別に管理することになる。
  symlinkを張ることでプロジェクトと一緒に管理できる

Nginxの設定&起動

gunicornはPythonを実行するソフトウェアであるため負荷が大きい。そのためHTML,CSS,Javascript等静的ページをNginxに配置することで、必要な時だけPythonを呼び出す構成にする。

Djangoアプリ用のファイル作成

/etc/nginx/sites-available/(プロジェクトディレクトリ名)
server {
        listen 80;
        server_name (ドメイン名 or グローバルIP);

location = /favicon.ico {access_log off; log_not_found off;}

location /static/ {
root /home/ubuntu/(プロジェクトディレクトリ名);
}

location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/(プロジェクトディレクトリ名)/(プロジェクトディレクトリ名).sock;
}

シンボリックリンクを作成

sudo ln -s /etc/nginx/sites-available/(プロジェクトディレクトリ名) /etc/nginx/sites-enabled/

作成したファイルの内容が正しいか確認

sudo nginx -t

Nginx再起動

sudo systemctl restart nginx

Ubuntuファイアウォールの設定

ファイアウォールで80ポートに穴をあける

(もし開放していたら)試験的に開放していた8000ポートを閉じる

sudo ufw delete allow 8000

Nginxのアクセスを許可する

 sudo ufw allow ’Nginx  Full’

問題発生

download.png

/var/log/nginx/error.logを確認。すると

unix:/home/ubuntu/(プロジェクトディレクトリ名)/(プロジェクトディレクトリ名).sock failed (13: Permission denied)

となっていたため、

以下のファイルを次のように編集

/etc/nginx/nginx.conf
- user www-data
+ user root

で解決

AWSの設定&確認

AWS > EC2 > インバウンドルールに80ポートの開放を追加

http://(グローバルIP)でアクセスできるか確認


補足 : Nginxの設定sites-available, sites-enabledの解説
https://qiita.com/tomokon/items/e782636c1e5ec6b5dfdc

参考記事
https://ja.wikipedia.org/wiki/Nginx
https://pala-ghe.com/aws-ec2-django-2-gunicorn-nginx/

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2