我正在尝试建立一个使用django框架编写的简单博客网站。除了不提供静态文件外,该网站还能正常工作。我想那是因为nginx没有运行。然而,当我将其配置为在80以外的任何端口上运行时,我会收到以下错误:
nginx: [emerg] bind() to 172.17.0.1:9000 failed (99: Cannot assign requested address)
当我在gunicorn已经使用的端口上运行它时,我会得到以下错误:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
我的nginx配置文件如下:
upstream django {
server 127.0.0.1:8080;
}
server {
listen 172.17.0.1:9000;
server_name my.broken.blog;
index index.html;
location = /assets/favicon.ico { access_log off; log_not_found off; }
location /assets {
autoindex on;
alias /var/www/html/mysite/assets;
}
location / {
autoindex on;
uwsgi_pass unix:///run/uwsgi/django/socket;
include /var/www/html/mysite/mysite/uwsgi_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
但如果我在没有启动guincorn的情况下运行nginx,它会正常运行,但我会得到一个403禁止的错误。
按照建议的答案,我没有得到任何错误,但该网站返回403禁止,并且没有提供gunicorn应该提供的网站部分。
以以下方式配置Nginx和Gunicorn以使其工作,
- 使用unix套接字在nginx和gunicron之间混合,而不是在某些端口中运行gunicorn
在以下位置为gunicorn创建一个单位文件
sudo nano /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=root
Group=nginx
WorkingDirectory=/path-to-project-folder
ExecStart=/<path-to-env>/bin/gunicorn --workers 9 --bind unix:/path-to-sockfile/<blog>.sock app.wsgi:application
Restart=on-failure
[Install]
WantedBy=multi-user.target
然后启动并启用gunicorn服务它将在指定的路径中生成一个sock文件。
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
注意:为gunicorn选择合适数量的工人,可以按照以下指定日志文件
ExecStart=//bin/gunicorn--workers 9--将unix:/path绑定到sockpile/.sock-app.wsgi:application--访问日志文件/var/log/gunicorn/access.log--错误日志文件/var/log/error.log
- 在/ect/nginx中创建一个特定于项目的新配置文件,而不是编辑默认的nginx.conf
nano/etc/nginx/blog.conf
并添加以下行(也可以在/etc/nginx/default.d/中添加文件(
server {
listen 80;
server_name 172.17.0.1; # your Ip
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path-to-static-folder;
}
location /media/ {
root /path-to-media-folder;
}
location / {
proxy_set_header Host $http_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;
proxy_pass http://unix:/path-to-sock-file/<blog-sock-file>.sock;
}
}
包括/etc/nginx/blog.conf到nignx.conf
---------
----------
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/blog.conf; # the new conf file added
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
------
-------
运行sudonginx-t//检查nginx配置中的错误
运行sudo systemctl nginx重新启动
参考:https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04