Gunicorn 是一個由純Python實現的UNIX類操作系統平台下WSGI服務,它非常容易部署和使用,而且沒有別的依賴
我使用的是nginx+gunicorn進行部署,如果你願意,你用可以只使用Gunicorn
另外,這個方法只適用於linux系統下
你可以單純使用命令 ``nohup gunicorn deeru.wsgi & `` 運行,但這樣一旦gunicorn意外停止,你的網站就無法訪問。
官方介紹了Gaffer、Runit、Supervisor等多種工具幫助你以守護進程的方式運行,詳見:http://docs.gunicorn.org/en/stable/deploy.html#monitoring
新建 /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
PIDFile=/run/gunicorn/pid
# 改為你自己的用戶
User=someuser
Group=someuser
RuntimeDirectory=gunicorn
# DeerU路徑
WorkingDirectory=/home/xxx/DeerU
# 如果是用了虛擬環境,需要用虛擬環境中gunicorn的絕對路徑 '/home/xx/deeru_env/bin/gunicorn'
# workers單核cpu建議不超過2
# 其他參數參照gunicorn文檔
# 我socket來進行nginx與gunicorn之間的的通信,你也可以改為tcp方式--bind 127.0.0.1:9001 ,這里不再敘述tcp通信方式的配置
ExecStart=/home/xx/deeru_env/bin/gunicorn --workers 2 --pid /run/gunicorn/pid --bind unix:/run/gunicorn/socket deeru.wsgi
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
新建 /etc/systemd/system/gunicorn.socket:
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn/socket
[Install]
WantedBy=sockets.target
新建 /etc/tmpfiles.d/gunicorn.conf
d /run/gunicorn 0755 someuser somegroup -
設置開機啟動並開始gunicorn services:
systemctl enable gunicorn.socket
systemctl start gunicorn.socket
修改nginx配置:
...
http {
...
upstream app_server {
server unix:/tmp/gunicorn.sock fail_timeout=0;
# TCP 方式改為
# server 192.168.0.7:8000 fail_timeout=0;
}
server {
...
listen 80;
location / {
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
proxy_pass http://app_server;
}
# 靜態文件
location ~ ^/(static|media)/ {
root /home/xxx/project/DeerU;
add_header Access-Control-Allow-Origin *;
expires 864000;
}
}
}