因为 gunicorn 是您案例中的 Web 服务器,所以 Nginx 将充当反向代理,将 HTTP 请求从 Nginx 传递到 gunicorn。
因此,我将在这里介绍在同一台机器上运行简单的 Nginx 和 Gunicorn 配置的步骤。
转到您的/etc/nginx/nginx.conf并在 http{} 下确保您有: include /etc/nginx/site-enabled/*;
http{
# other configurations (...)
include /etc/nginx/sites-enabled/*;
}
现在,在 /etc/nginx/sites-enabled/mysite.conf 中包含一个文件,您将在其中将您的请求代理到您的 gunicorn 应用程序。
server {
listen 80 default; # this means nginx will be
# listening requests on port 80 and
# this will be the default nginx server
server_name localhost;
# declare proxy params and values to forward to your gunicorn webserver
proxy_pass_request_headers on;
proxy_pass_request_body on;
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_read_timeout 120s;
location / {
# here is where you declare that every request to /
# should be proxy to 127.0.0.1:8000 (which is where
# your gunicorn will be running on)
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://127.0.0.1:8000/; # the actual nginx directive to
# forward the request
}
}
好的,此时您所拥有的只是一个充当代理的 Nginx,其中所有发往 127.0.0.1:80 的请求将被传递到 127.0.0.1:8000。
- 现在是时候配置你的Gunicorn 网络服务器了:
通常我使用配置文件的方式是,Gunicorn 配置文件可以是一个普通的 python 文件。所以现在,在你喜欢的任何位置创建一个文件,我假设这个文件是/etc/gunicorn/mysite.py
workers = 3 # number of workers Gunicorn will spawn
bind = '127.0.0.1:8000' # this is where you declare on which address your
# gunicorn app is running.
# Basically where Nginx will forward the request to
pidfile = '/var/run/gunicorn/mysite.pid' # create a simple pid file for gunicorn.
user = 'user' # the user gunicorn will run on
daemon = True # this is only to tell gunicorn to deamonize the server process
errorlog = '/var/log/gunicorn/error-mysite.log' # error log
accesslog = '/var/log/gunicorn/access-mysite.log' # access log
proc_name = 'gunicorn-mysite' # the gunicorn process name
好的,所有设置都在配置中。现在你要做的就是启动服务器。
启动 gunicorn 并告诉它使用哪个应用程序和哪个配置文件。从命令行和myapp.py文件所在的文件夹运行:
gunicorn -c /etc/gunicorn/mysite.py mysite:app
现在,只启动 nginx。
/etc/init.d/nginx start
或者
service nginx start
希望这可以帮助。