搭建nginx+uwsgi+django
下载uwsgi
pip3 install uwsgi
测试uwsgi是否能正常使用
创建py文件,包含如下内容
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]
通过8001端口,启动test.py
uwsgi --http :8001 --wsgi-file test.py
下载nginx
apt install nginx
下载完成自动启动,默认80端口是nginx的欢迎页
/etc/init.d/nginx restart
uwsgi启动django
在保证uwsgi可用之后,接下来用uwsgi来启动django
[uwsgi]
#使用nginx连接时使用
#socket=127.0.0.1:8080
#直接做web服务器使用
http=:8080
#项目目录
chdir=/home/shuan/dailiyfresh
#项目中wsgi.py文件的目录,相对于项目目录
wsgi-file=dailiyfresh/wsgi.py
# 指定启动的工作进程数
processes=4
# 指定工作进程中的线程数
threads=2
master=True
# 保存启动之后主进程的pid
pidfile=uwsgi.pid
# 设置uwsgi后台运行,用uwsgi.log保存日志信息
# daemonize=uwsgi.log
# 设置虚拟环境的路径
# virtualenv=/home/shuan/.virtualenvs/bj18_py3
*:注意指定http时,如果是云服务器前面不要补全127.0.0.1;socket不是用nginx时,可以先不指定
通过8080端口即可访问我们的项目。
重启uwsgi
当通过uwsgi启动django,更新代码uwsgi不会重新加载代码,需要重启uwsgi
# 通过配置启动uwsgi
uwsgi --ini uwsgi.ini
# 关闭所有uwsgi
killall -9 uwsgi
配置nginx
# 备份原配置
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
# 建立软连接至项目目录,方便管理
ln -s /etc/nginx/nginx.conf nginx.conf
然后在nginx.conf的http内,添加如下子项;此处最关键的参数是listen和uwsgi_pass的端口对应,listen就是我们外部访问的端口,uwsgi_pass一定要与uwsgi配置中的socket端口对应。
server {
listen 8081;
server_name 140.143.137.193;
access_log /home/zjm/project/learn_django/log/nginx/access.log;
error_log /home/zjm/project/learn_django/log/nginx/error.log;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
include /etc/nginx/uwsgi_params;
uwsgi_pass 127.0.0.1:8080;
}
error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location /static/ {
alias /home/zjm/project/learn_django/static/;
}
location /templates/ {
alias /home/zjm/project/learn_django/templates/;
}
}
配置完nginx后,/etc/init.d/nginx restart
重启生效
*此处我绑定了域名950601.xyz
常用nginx命令
# 启动nginx
/etc/init.d/nginx start
# 重启
/etc/init.d/nginx restart
# 停止
/etc/init.d/nginx stop