ConohaでUbuntu 18.04のVPSを立ち上げ、Djangoをデプロイ(Nginx+Gunicorn)


実際の処理はrootユーザで行っているので、sudoいらないのだが、色々なところからのコピペコマンドだったりするので、そのまま残して書いてあるところがあります。

下準備と必要なソフトウェアのインストール

passwd
(パスワード変更)

shutdown -r now
(一度再起動)
(再ログイン)

sudo apt update

sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl

PostgreSQLの設定

sudo -u postgres psql

CREATE DATABASE Database名;
CREATE USER DBユーザ名 WITH PASSWORD 'DBパスワード';
ALTER ROLE DBユーザ名 SET client_encoding TO 'utf8';
ALTER ROLE DBユーザ名 SET default_transaction_isolation TO 'read committed';
ALTER ROLE DBユーザ名 SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE Database名 TO DBユーザ名;

\q

Virtual Environmentの導入

sudo -H pip3 install --upgrade pip
sudo -H pip3 install virtualenv

Django用のディレクトリを作成

cd /home
mkdir django
cd django

(開発環境で作成したDjangoのデータを/home/djangoディレクトリ配下にコピー)

Virtual環境を作成してActivate

cd testdjango( <-Djangoのプロジェクト名)
virtualenv venv
source venv/bin/activate

Djangoに必要なソフトウェアのインストール

pip install django gunicorn psycopg2-binary
pip install django-allauth
pip install django-cleanup
pip install pillow

Djangoの設定ファイルの変更/修正

vi /home/django/testdjango/testdjango/settings.py

ALLOWED_HOSTS = ['VPSのIP', ‘localhost']

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'Database名',
'USER': 'DBユーザ名',
'PASSWORD': 'DBパスワード',
'HOST': 'localhost',
'PORT': '',
}
}

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
(# STATICFILES_DIRSセクションをコメントアウト)
(:wqでviを抜ける)

Djangoの設定

python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic
 (Type 'yes' to continue, or 'no' to cancel: yes)
python manage.py createsuperuser

gunicornの動作確認

sudo ufw allow 8000
gunicorn --bind 0.0.0.0:8000 testdjango.wsgi
(WebブラウザからVPSのIPアドレス:8000にアクセスを確認。確認が出来たらCtrl+cでgunicornを停止)
deactivate

gunicornの設定

sudo vim /etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target

sudo vim /etc/systemd/system/gunicorn.service

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/home/django/testdjango
ExecStart=/home/django/testdjango/venv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
testdjango.wsgi:application

[Install]
WantedBy=multi-user.target

gunicornの起動(と自動起動)

sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket

nginxの設定

sudo vim /etc/nginx/sites-available/testdjango

server {
listen 80;
server_name VPSのIP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/django/testdjango;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}

実際にnginxが使用するファイルとして認識させる(ためにシンボリンクリンクを作成)

sudo ln -s /etc/nginx/sites-available/testdjango /etc/nginx/sites-enabled

nginxの再起動とファイアウォールの設定

sudo systemctl restart nginx
sudo ufw allow 'Nginx Full'

(アクセスを確認)