使用uwsgi部署Django應用
一、打包Django應用
1.建立setup.py檔案
from setuptools import setup import glob setup(name='blog', version='1.0', description='blog project', author='Keith', author_email='[email protected]', url='https://www.python.org/', packages=['blog', 'user', 'post'], py_modules=['manage'], data_files=glob.glob('templates/*.html') + ['requirements'] )
2.儲存專案中使用的庫
pip freeze > requirements
3.打包原始碼
python3 setup.py sdist
二、在部署server上安裝依賴包
pip3 install -r requirements
三、修改Django配置檔案
sed -i -e 's/DEBUG.*/DEBUG = False/' -e 's/ALLOWED_HOSTS.*/ALLOWED_HOSTS = ["*"]/' blog/settings.py
四、測試執行
python3 manage.py runserver 0.0.0.0:8001
第一種部署方式,直接以http方式啟動
1.安裝uwsgi
pip3 install uwsgi
2.執行app
uwsgi --http :8001 --wsgi-file blog/wsgi.py --stats :8002 --stats-http
3.測試訪問
http://ip:8001/post/?page=1&size=2
4.檢視server狀態
http://ip:8002/
第二種部署方式,提供配置檔案,以socket方式執行
1.建立配置檔案blog.ini,放在專案根目錄下
[uwsgi] socket = 127.0.0.1:8001 chdir = /opt/blog-1.0/ wsgi-file = blog/wsgi.py master = true workers = 3 stats = 127.0.0.1:8002 stats-http = true
2.執行app
uwsgi blog.ini
第三種部署方式,使用systemd管理uwsgi
1.建立service檔案
vim /usr/lib/systemd/system/blog.service
[Unit]
Description=uWSGI Emperor
After=syslog.target
[Service]
ExecStart=/usr/local/bin/uwsgi --ini /opt/blog-1.0/blog.ini
# Requires systemd version 211 or newer
RuntimeDirectory=uwsgi # 會建立/var/run/uwsgi目錄
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all
[Install]
WantedBy=multi-user.target
2.啟動服務
systemctl start blog.service
systemctl status blog.service
systemctl enable blog.service
還有一個重要的部分,那就是提供Nginx代理
1、安裝tengine,很簡單,過程略...
2、修改Nginx配置
server {
listen 80;
server_name localhost;
# http代理
# location ^~ /api/ {
# rewrite ^/api(/.*) $1 break;
# proxy_pass http://127.0.0.1:8001;
# }
# socket代理
location ^~ /api/ {
rewrite ^/api(/.*) $1 break;
include uwsgi_params;
uwsgi_pass 127.0.0.1:8001;
}
# 根路徑,通常是前端SPA單頁面應用的入口
location / {
root html;
index index.html index.htm;
}
}
3、啟動Nginx服務
到這裡,後端應用基本部署完成。
再把前端檔案部署好,通過Nginx動靜分離就完整了,這裡就不說前端應用了。
另外,還有一種常見的部署方式,就是通過supervisord等這類程序管理服務來執行app,這裡也不細說了。
參考:
https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#deploying-django
https://uwsgi-docs.readthedocs.io/en/latest/StatsServer.html
https://uwsgi-docs.readthedocs.io/en/latest/Systemd.html
https://uwsgi-docs.readthedocs.io/en/latest/Configuration.html
http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html