1、打包Django應用html
1.建立setup.py文件前端
from setuptools import setup import glob setup(name='blog', version='1.0', description='blog project', author='Keith', author_email='329640305@qq.com', url='https://www.python.org/', packages=['blog', 'user', 'post'], py_modules=['manage'], data_files=glob.glob('templates/*.html') + ['requirements'] )
2.保存項目中使用的庫python
pip freeze > requirements
3.打包源碼nginx
python3 setup.py sdist
2、在部署server上安裝依賴包django
pip3 install -r requirements
3、修改Django配置文件vim
sed -i -e 's/DEBUG.*/DEBUG = False/' -e 's/ALLOWED_HOSTS.*/ALLOWED_HOSTS = ["*"]/' blog/settings.py
4、測試運行後端
python3 manage.py runserver 0.0.0.0:8001
第一種部署方式,直接以http方式啓動api
1.安裝uwsgiapp
pip3 install uwsgi
2.運行appsocket
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代理
一、安裝tengine,很簡單,過程略...
二、修改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; } }
三、啓動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