美文网首页django_学习笔记
django + nginx + gunicorn + ubun

django + nginx + gunicorn + ubun

作者: Shun2018 | 来源:发表于2019-02-15 11:38 被阅读0次

一、安装nginx

sudo apt install nginx -y

二、安装gunicorn

注意:要在项目的虚拟环境目录下使用pip安装gunicorn

pip install gunicorn

编辑项目根目录下的settings.py,添加 ‘gunicorn’

INSTALLED_APPS = [
    'mycommon.apps.CommonConfig',
    # 'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gunicorn',    #将gunicorn添加进来
]

三、配置nginx

cd /etc/nginx/sites-enabled #进入nginx配置目录
sudo vim default #编辑配置文件

server {
        listen   80; #监听端口号
        server_name 192.168.2.195; #如果没有域名,就使用本机IP
        server_name_in_redirect off;
        access_log  /var/log/nginx/yd-access.log; #访问日志文件
        error_log  /var/log/nginx/yd-error.log; #错误日志文件


        location / { # 配置代理转发
                proxy_pass http://0.0.0.0:8000;
                proxy_pass_header       Authorization;
                proxy_pass_header       WWW-Authenticate;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /static/ { # 静态文件
                root /home/ydbz/ydbz/ydsite/;
        }

}

四、启动服务

1、nginx服务

sudo service nginx start # 启动nginx服务
sudo service nginx stop # 停止nginx服务
sudo service nginx reload # 重新加载nginx服务

2、gunicorn服务

cd /path/to/django/sitename/ #切换目录到项目根目录
gunicorn sitename.wsgi #启动项目(项目根目录.wsgi)

五、配置gunicorn开机启动

编辑 /etc/rc.local 文件,添加启动gunicorn代码,保证在exit 0这行之前写完启动代码。

~/.pyenv/versions/ydbz/bin/gunicorn --chdir /home/ydbz/ydbz/ydsite ydsite.wsgi &

注意:
1、要使用虚拟环境下的gunicorn命令;
2、--chdir 指定项目根目录:/home/ydbz/ydbz/ydsite
3、指定应用模块:项目名.wsgi
4、由于该命令不会马上执行完,会有阻塞,在命令最后要使用 & 符合结尾,使该命令在其他进程执行。

六、gunicorn异步模式(默认启动为同步模式)

使用场景:进度条加载需要异步请求(不断地从服务器获取进度值返还给前端显示)
1、安装所需组件gevent:

pip install gevent

2、启动gunicorn异步模式(加上: -k 'gevent 选项即可):

gunicorn --access-logfile access_file.log --error-logfile error_file.log -k 'gevent' ydsite.wsgi

七、uWSGI异步模式(默认启动为同步模式)

1、安装uWSGI:

pip install uwsgi

2、启动uWSGI异步模式(加上: --async 选项即可):

uwsgi --http :8888 --module wsgi -l 1000 --async 100 --ugreen

3、也可以将配置信息单独写进一个配置文件里面:(例如项目根目录下创建配置文件:uwsgi.ini)

wsgi-file = ydsite/wsgi.py
  
# 进程个数
workers=5
pidfile=uwsgi.pid

# 指定IP端口 使用http可直接通过浏览器直接访问
http = 0.0.0.0:9090
socket =0.0.0.0:9090

# 启用主进程
master=true

# 自动移除unix Socket和pid文件当服务停止的时候
vacuum=true

# 开启异步
async=true

# 序列化接受的内容,如果可能的话
thunder-lock=true

# 启用线程
enable-threads=true

# 设置自中断时间
harakiri=30

# 设置缓冲
post-buffering=4096

# 设置日志目录
daemonize=uwsgi.log

# 权限
chmod-socket=666

相关文章

网友评论

    本文标题:django + nginx + gunicorn + ubun

    本文链接:https://www.haomeiwen.com/subject/tslpeqtx.html