当前位置 主页 > 网站技术 > 代码类 >

    浅谈Django+Gunicorn+Nginx部署之路(2)

    栏目:代码类 时间:2019-09-11 18:09

    之后可用通过如下方式启动我们的网站:

    # 启动方式(首先需要切换到项目根目录,即和 manage.py 在同级目录下):gunicorn -c gunicorn.conf.py website.wsgi:application# 或gunicorn website.wsgi:application -b 0.0.0.0:8000 -w 4 -k gthread# 或gunicorn website.wsgi:application -b 0.0.0.0:8000 -w 4 -k gthread --thread 40 --max-requests 4096 --max-requests-jitter 512# 查看进程ps aux | grep gunicorn

    步骤三

    配置 Nginx

    通过前两步,我们可以成功将我们的网站跑起来,但是目前还只能在内部访问,所以我们需要通过 Nginx 来做反向代理,供外网访问。

    执行下述命令进行安装和配置

    sudo apt-get install nginxsudo service nginx start# 备份默认配置sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak# 启动 Vim 修改我们的网站配置sudo vim /etc/nginx/sites-available/default

    示例配置如下所示:

    server{    ...    server_name hippiezhou.fun *.hippiezhou.fun;    access_log /var/log/nginx/access.log;    error_log /var/log/nginx/error.log;    ...    location / {        # First attempt to serve request as file, then        # as directory, then fall back to displaying a 404.        # try_files $uri $uri/ =404;        proxy_pass     http://127.0.0.1:8000; #此处要和你 gunicore 的 ip 和端口保持一致        proxy_redirect   off;        proxy_set_header  Host         $host;        proxy_set_header  X-Real-IP      $remote_addr;        proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;        proxy_set_header  X-Forwarded-Proto  $scheme;    }    location /static {        alias /root/hippiezhou.fun/src/staticfiles; # 此次需要配置为你的网站对应的静态资源的绝对路径    }    location /media {        alias /root/hipiezhou.fun/src/media; # 如果你的网站有上传功能,需要配置该结点并指向目标路径    }    ...}

    配置完成后执行下述操作即可将我们的网站运行起来

    # 若网站未启动执行该命令gunicorn -c gunicorn.conf.py website.wsgi:applicationsudo nginx -tsudo service nginx restart

    如果不出意外,网站应该是可以正常访问,如果静态资源依然不能访问,打开网站的 开发者工具看一下是什么错误。

    如果是 404 的问题,请确保你的 settings 相关配置和我上面列出来的是一致的; 如果是 403 的问题,应该是 Nginx 无权访问你指定的静态资源,你需要修改 Nginx 的用户类型,亲执行下述命令
    sudo vim /etc/nginx/nginx.conf

    将 user 后面的值修改为 root,然后重启 Nginx 即可。

    最后,关于如何配置 HTTPS,这里就不过多介绍了,直接列出相关示例脚本:

    sudo apt-get updatesudo apt-get install software-properties-commonsudo add-apt-repository universesudo add-apt-repository ppa:certbot/certbotsudo apt-get updatesudo apt-get install certbot python-certbot-nginxsudo certbot --nginx# sudo certbot renew --dry-runsudo ufw allow httpssudo systemctl restart nginx

    总结

    在部署的过程中,其实遇到最多的问题就是关于静态资源无法问题的问题,但是看到网上很多文章,都不一样,并且有的写的还是错误的。所以这里就总结一些。还好,一切顺利。算是填了 4 年前的一个坑吧。