博主在虚拟环境下部署的
1 配置gunicorn
想用python3 跑程序那就 pip3 install gunicorn
在你的工程下边 新建一个gunicorn的配置文件目录在该目录下 新建一个gunicorn的配置文件 内容如下
command = '/home/ubuntu/.local/bin/gunicorn' #命令(绝对路径)
pythonpath = '/home/ubuntu/user/项目代码' #这个路径是你Django项目的路径 这个路径下边要包含manage.py
bind = '127.0.0.1:12356' #你服务运行的端口
#bind = '0.0.0.0:12356' 看自己
workers = 2 #表示开几个线程去相应浏览器请求
#注意:gunicorn的路径 是在执行了which gunicorn得到的路径
测试:在包含manage.py文件的目录下运行类似下面的命令
gunicorn 工程名字.wsgi -c gunicorn配置文件夹/配置文件
2 配置nginx
sudo apt install nginx
在/etc/nginx/conf.d 目录下 新建一个 你的配置文件.conf
加入类似的配置
server{
listen 80;
server_name ip/www; #此处写你的域名或者ip
location / {
proxy_pass http://127.0.0.1:12356; #你Django服务跑的那个端口
proxy_set_header Host $host;
#捕获客户端真实IP
proxy_set_header X-Real-IP $remote_addr; #$remote_addr 代表客户端IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static{
alias /home/ubuntu/user/项目代码/static/; #静态文件的配置 路径就是你Django的static目录的路径
}
}
修改完配置 执行 sudo nginx -s reload
负载均衡的配置
upstream axf{
server ip:12356 weight=2;
server ip:12355 weight=3;
}
server{
listen 80;
server_name ip/www; #此处写你的域名或者ip
location / {
proxy_pass http://www;
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 /home/路径/static;
}
}
3配置supervisor
安装:sudo apt install supervisor
在/etc/supervisor/conf.d 目录下新建你的配置文件.conf 内容如下
[program:项目名/app名都可以]
directory=/home/ubuntu/user/项目代码
command=/home/ubuntu/.local/bin/gunicorn 工程名字.wsgi -c gunicorn配置文件夹/配置文件
autostart=true
startsecs=10
autorestart=true
startretries=3
user=当前用户名
priority=999
redirect_stderr=true
stdout_logfile_maxbytes=100MB
stdout_logfile_backups = 20
stdout_logfile=/var/log/supervisor_logs/axf.log
stopasgroup=false
killasgroup=false
带注释的版本
[program:axf]
directory=/home/ubuntu/user/项目代码
command=gunicorn pro.wsgi -c service_conf/django_gunicorn.conf ; 程序启动命令
autostart=true ; 在supervisord启动的时候也自动启动
startsecs=10 ; 启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒
autorestart=true ; 程序退出后自动重启,可选值:[unexpected,true,false],默认为unexpected,表示进程意外杀死后才重启
startretries=3 ; 启动失败自动重试次数,默认是3
user=root ; 用哪个用户启动进程,默认是root
priority=999 ; 进程启动优先级,默认999,值小的优先启动
redirect_stderr=true ; 把stderr重定向到stdout,默认false
stdout_logfile_maxbytes=100MB ; stdout 日志文件大小,默认50MB
stdout_logfile_backups = 20 ; stdout 日志文件备份数,默认是10
; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile=/var/log/supervisor_logs/程序.log # supervisor_logs需要自己创建 axf.log博主自己建的,应该是自己生成
stopasgroup=false ;默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程
killasgroup=false ;默认为false,向进程组发送kill信号,包括子进程
修改完以后
重新加载配置文件 执行命令:
sudo supervisorctl reload
sudo supervisorctl restart all(你想重启的单个应用名字也可以)
查看状态
sudo supervisorctl status
如果启动问题 先去看看log log的位置 stdout_logfile=/var/log/supervisor_logs/程序.log
看到不明白的地方,下面评论,看到会回复