Background

最近在玩Django, 所以紀錄一下怎麼設定. 感覺之後如果要Run整個Web Service的話會使用Django, 要使用Api Service的話則會用Flask.

Install

我自己是用 python3, 所以之後的例子都是以 python3 來介紹

最終想要的整體流程如下

the web client <-> the web server <-> the socket <-> uwsgi <-> Django

所以就開始囉.

$ sudo apt-get update
$ sudo apt-get install python3-pip python3-dev

在 python 的開發環境中, 我們通常會使用虛擬環境來切割不同專案以方便管理. 所以需安裝 virtualenv.

$ sudo pip3 install virtualenv
$ sudo pip3 install Django

Create Django Projects

$ sudo mkdir /var/www
$ cd /var/www
$ sudo django-admin.py startproject MYSITE
$ sudo chown -R USER:root ./MYSITE/
$ cd MYSITE
$ virtualenv .venv
# switch virtual env
$ source .venv/bin/activate
$ pip install Django
$ mkdir log 

加入host的相關資訊

MYSITE/settings.py

# The simplest case: just add the domain name(s) and IP addresses of your Django server
# ALLOWED_HOSTS = ['example.com', '123.123.123.123']

因為希望在未來可以讓 Nginx 可以直接使用靜態檔案, 所以需新增以STATIC_ROOT路徑.

MYSITE/settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
# create static folder
$ ./manage.py collectstatic
$ deactivate

Setting up the uWSGI Application Server

$ sudo pip3 install uwsgi
# place conf files
$ sudo mkdir -p /etc/uwsgi/sites
$ cd /etc/uwsgi/sites
$ sudo vim MYSITE.ini

/etc/uwsgi/sites/MYSITE.ini

[uwsgi]
project = MYSITE
uid = USER
gid = www-data
base = /var/www

# Django 主目錄的路徑
chdir = %(base)/%(project)
# 虛擬環境的目錄路徑
home = %(base)/%(project)/.venv
module = %(project).wsgi

master = true
processes = 5

socket = /run/uwsgi/%(project).sock
chown-socket = %(uid):www-data
chmod-socket = 660

vacuum = true
logto = %(base)/%(project)/log/%(project).log

完成後我們需要設定 systemd Unit File for uWSGI 讓開機時可以自動呼叫 uWSGI service.

$ sudo vim /etc/systemd/system/uwsgi.service

/etc/systemd/system/uwsgi.service

參考官網的介紹

[Unit]
Description=uWSGI Emperor service

[Service]
ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown USER:www-data /run/uwsgi'
ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all

[Install]
WantedBy=multi-user.target

Install and Configure Nginx

$ sudo apt-get install nginx
$ sudo vim /etc/nginx/sites-available/MYSITE

/etc/nginx/sites-available/MYSITE

server {
    listen 80;
    server_name MYSITE.com IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/MYSITE;
    }

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/run/uwsgi/MYSITE.sock;
    }
}
# create soft link
$ sudo ln -s /etc/nginx/sites-available/MYSITE /etc/nginx/sites-enabled
# test nginx conf file is correct or not
$ sudo nginx -t

如果沒問題之後就重啟相關服務

sudo systemctl restart nginx
sudo systemctl start uwsgi
sudo systemctl enable nginx
sudo systemctl enable uwsgi

接下來在瀏覽器上輸入ip or 網址就會看到類似下圖.

Reference