安装uwsgi:pip install uwsgi
安装nginx: yum install nginx
示例django项目路径结构:
|-- db.sqlite3
|-- manage.py
|-- samp
| |-- init.py
| |-- pycache
| |-- admin.py
| |-- apps.py
| |-- migrations
| |-- models.py
| |-- tests.py
| |-- urls.py
| -- views.py |-- sample | |-- __init__.py | |-- __pycache__ | |-- settings.py | |-- urls.py |
– wsgi.py
`-- wsgi.ini
- 进入根路径(我的根路径为/data/joffreywang/test/sample),使用uwsgi启动django服务
uwsgi --socket sample_wsgi.sock --module sample.wsgi --chmod-socket=777
- 在/etc/nginx/conf.d/路径添加自己的nginx配置文件,我这里监听的是8888端口
# mysite_nginx.conf
# the upstream component nginx needs to connect to
#upstream django {
# server unix:///home/joffreywang/test/django/scripts/sample/sample_wsgi.sock; # for a file socket
# server unix:///home/joffreywang/test/django/scripts/sample/sample.sock; # for a web port socket (we'll use this first)
#server 127.0.0.1:8889;
#}
# configuration of the server
server {
# the port your site will be served on
listen 8888;
# the domain name it will serve for
server_name _; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
#location /media {
# alias /path/to/your/mysite/media; # your Django project's media files - amend as required
#}
#location /static {
# alias /path/to/your/mysite/static; # your Django project's static files - amend as required
#}
# Finally, send all non-media requests to the Django server.
location / {
#uwsgi_pass django;
#include /home/joffreywang/test/django/scripts/sample/uwsgi_params; # the uwsgi_params file you installed
include uwsgi_params;
uwsgi_pass unix:/data/joffreywang/test/sample/sample_wsgi.sock;
}
}
- 重启nginx
nginx -s stop
nginx -c /etc/nginx/nginx.conf
然后便可以使用ip:port访问django服务
说明:
- 可以使用ini文件配置代替uwsgi启动的参数。我的示例wsgi.ini文件:
[uwsgi]
socket = /data/joffreywang/test/sample/sample_wsgi.sock
chdir = /data/joffreywang/test/sample
wsgi-file = sample/wsgi.py
processes = 4
threads = 2
master=True
pidfile= /data/joffreywang/test/sample/sample_wsgi.pid
vacuum=True
daemonize = uwsgi.log
启动命令: uwsgi wsg.ini
2. 起初部署总是不成功,在stackoverflow上面找到了这个坑的原因__“If you put helloworld.sock file in your home directory, you’ll always get Permission denied.”__, 把项目放在数据盘就成功了
https://stackoverflow.com/questions/22071681/permission-denied-nginx-and-uwsgi-socket/40041214
3. django的wsgi启动文件创建项目时会自动生成,在project路径下,名为wsgi.py
4. uwsgi可以通过指定端口和协议启动,可以用在项目调试阶段。注意使用socket模式会自动关联一些第三方路由,如include /etc/nginx/uwsgi_params,配置nginx前,可能会导致web无法直接访问
uwsgi --http :8888 --module sample.wsgi
uwsgi --http :8001 --wsgi-file sample/wsgi.py
uwsgi --socket :8888 --wsgi-file sample/wsgi.py
uwsgi --socket :8811 --module sample.wsgi
- 安装uwsgi时,需要编译,在在Debian和衍生的Ubuntu上面安装时,要先装python开发版和gcc
sudo apt-get install python3-dev
sudo apt-get install gcc
官方文档:https://uwsgi-docs-zh.readthedocs.io/zh_CN/latest/tutorials/Django_and_nginx.html