部署:Nginx+Gunicorn+Venv+Supervisor+Django

3 篇文章 0 订阅
2 篇文章 0 订阅

项目路径:/home/zyh/projects/mytestProject1/mysite

一:添加虚拟环境venv

  1. 切换到项目路径

     cd /home/zyh/projects/mytestProject1/mysite 
    
  2. 新建虚拟环境python3_venv

     python -m venv python3_venv 
    
  3. 激活

     source python3_venv/bin/activate
    
  4. 下载项目所需第三方库

     pip install -r requirements.txt 
    

二:配置Gunicorn

  1. 虚拟环境中安装gunicorn

     pip install gunicorn 
    
  2. 测试开启服务(可选):

     cd /home/zyh/projects/mytestProject1/mysite
     gunicorn mysite.wsgi:application --bind 127.0.0.1:9000 # 9000 为gunicorn端口
    
  3. 编写gunicorn脚本文件(linux中:set ff=unix)

     1. cd /home/zyh/projects/mytestProject1/mysite
     2. touch gunicorn_start.sh # 新建gunicorn文件
    
  4. 插入代码

     #!/bin/bash
     NAME="mysite"
     DIR=/home/zyh/projects/mytestProject1/mysite
     USER=zyh
     GROUP=zyh
     WORKERS=3
     BIND=127.0.0.1:9000
     DJANGO_SETTINGS_MODULE=mysite.settings
     DJANGO_WSGI_MODULE=mysite.wsgi
     LOG_LEVEL=error
    
     cd $DIR 
     source ../python3_venv/bin/activate
     export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
     export PYTHONPATH=$DIR:$PYTHONPATH
       
     exec ../python3_venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
       --name $NAME \
       --workers $WORKERS \
       --bind=$BIND \
       --log-level=$LOG_LEVEL \
       --log-file=-
    
  5. 修改权限为可执行模式

     sudo chmod u+x bin/gunicorn_start 
    

三:配置Supervisor

  1. 虚拟环境中安装supervisor

     pip install supervisor
    
  2. 生成配置文件

     cd /etc/supervisor
     echo_supervisord_conf > /etc/supervisord.conf 
     sudo vim supervisord.conf
    
  3. 修改代码

     [unix_http_server]
     file=/var/run/supervisor.sock (修改成当前)
     [inet_http_server]         ; inet (TCP) server disabled by default
     port=0.0.0.0:8080        通过网页管理
     username=admin              
     password=admin              
    
    
     [supervisord]
     logfile=/var/log/supervisord.log(修改成当前)
     pidfile=/var/run/supervisord.pid(修改成当前)
     [supervisorctl]
     serverurl=unix:///var/run/supervisor.sock(修改成当前)
     最后一行改为:files = /etc/supervisor/conf.d/*.conf
    
  4. 编辑自己的mysite.conf文件

     cd conf.d
     touch mysite.conf
    

    插入代码

     [program:mysite]
     directory=工作目录
     command=/home/zyh/projects/mytestProject1/mysite/gunicorn_start.sh(执行gunicorn文件)
     user=zyh
     autostart=true
     autorestart=true
     redirect_stderr=true
     stdout_logfile=/home/zyh/projects/mytestProject1/mysite/logs/robot.log
     stderr_logfile=/home/zyh/projects/mytestProject1/mysite/logs/err.log
     
     [program:celery]
     directory=/data_1/var/www/service_brain_model
     # -P为gevent或eventlet时,需要将beat和worker独立启动,-p=solo时不需要
     command=/bin/bash -c "source /data_1/var/www/venv/service_brain/bin/activate&&celery -A service_brain_model worker -B -l info  -P solo --without-gossip --without-mingle --without-heartbeat --logfile=logging/celery.log  --pidfile="
     autostart=true
     autorestart=true
     redirect_stderr=true
     stdout_logfile=/data_1/var/www/service_brain_model/logging/supervisor_celery_worker_access.log
     stderr_logfile=/data_1/var/www/service_brain_model/logging/supervisor_celery_worker.log
     environment=website_env=prod
     environment=PYTHONWARNINGS=ignore
     stopasgroup=true
     killasgroup=true
    
     
     ***********
    
  5. 也可以直接在supervisord.conf中插入代码

    删除最后一行files = /etc/supervisor/conf.d/*.conf

     [program:mysite]
     command =/home/zyh/projects/mytestProject1/mysite/gunicorn_start.sh(执行gunicorn文件)
     user = zyh
     autostart=true
     autorestart=true
     redirect_stderr = true
     stdout_logfile =/home/zyh/projects/mytestProject1/mysite/logs/robot.log
     stderr_logfile=/home/zyh/projects/mytestProject1/mysite/logs/err.log
    
  6. 新建logs文件夹

     cd /home/zyh/projects/mytestProject1/mysite
     mkdir logs
    
  7. 调试

     启动 
     	$ supervisord -c /etc/supervisor/supervisord.conf 
     	$ sudo supervisorctl reread 
     	mysite: available 
     	$ sudo supervisorctl update 
     	mysite: added process group
     查看所有服务状态	 
     	$ sudo supervisorctl status
     	mysite RUNNING pid 18020, uptime 0:00:50 
     停止服务	
     	$ sudo supervisorctl stop mysite
     	mysite: stopped 
     开启服务
     	$ sudo supervisorctl start mysite 
     	mysite: started 
     重启服务
     	$ sudo supervisorctl restart mysite / reload(全部)
     	mysite: stopped 
     	mysite: started
    

四:配置Nginx

	# 规则示范
	访问测试uriA: /api/docs/
	访问测试uriB: /media/xxx.png/
	访问测试uriC: /frontC/login/
	访问测试uriD: /frontD/login/
	location / {
		 proxy_pass http://127.0.0.1:9000/;  # A实际访问http://127.0.0.1:9000/api/docs/
	}
	location /api/ {
		 proxy_pass http://127.0.0.1:9000/;  # A实际访问http://127.0.0.1:9000/docs/
	}
	location /api/ {
		 proxy_pass http://127.0.0.1:9000/api/;  # A实际访问http://127.0.0.1:9000/api/docs/
	}
	location /media/ {
	    alias /home/zyh/mysite/meida/;  # B实际访问/home/zyh/mysite/meida/xxx.png
	}
	location /media/ {
	    alias /home/zyh/mysite/meida/;  # B实际访问/home/zyh/mysite/meida//xxx.png
	}
	location /media/ {
	    root /home/zyh/mysite/meida/;  # B实际访问/home/zyh/mysite/meida/meida/xxx.png
	}
	location /media {
	    root /home/zyh/mysite/meida/;  # B实际访问/home/zyh/mysite/meida/meida//xxx.png
	}
	location / {
        root   /usr/share/nginx/html/test;
        index  login.html index.htm;
    }
    location /frontC {
        alias   /usr/share/nginx/html/project01/;
        index  login.html index.htm;
        }
    location /frontD {
        alias   /usr/share/nginx/html/project02/;
        index  login.html index.htm;
    }
    总结1.localtion 中末尾带/ 转发的末尾也要带/。
    总结2.alias访问的是什么文件名就去指定目录里找,location的路径不存在时使用;
    root访问的需要去指定目录末尾再加一级location去找,location的路径存在时使用。   
  1. 下载

     sudo apt install nginx
    
  2. 新建dj.conf文件

     cd /etc/nginx/sites-available/
     touch dj.conf
    
  3. 插入代码

     server {
     listen 8000; # 监听端口(前端访问端口)
     server_name 192.168.153.189; # IP或者域名(前端访问)
     charset    utf-8;
     client_max_body_size 75M;
     location / {
     	 proxy_pass http://127.0.0.1:9000; # gunicorn的bind
     	 proxy_set_header Host $host;
     	 proxy_set_header X-Real-IP $remote_addr;
     	 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     }
     location /static {  #这里做了访问静态目录不走uwsgi/gunicorn
         #expires 30d;
         #autoindex on;
         #add_header Cache-Control private;
         alias /home/zyh/projects/mytestProject1/mysite/staticfiles/;  # django setting中static_root的路径
     	}
     }
    
  4. 创建软连接

     sudo ln -s /etc/nginx/sites-available/dj.conf /etc/nginx/sites-enabled/dj.conf # 必须为绝对路径
    
  5. 删除默认文件

     sudo rm /etc/nginx/sites-enabled/default
    
  6. 重启nginx

     sudo service nginx restart或sudo service nginx start
    

7.开机自启(可能已经自动添加了)

	vim /usr/lib/systemd/system/nginx.service
	写入:
	########################################
	[Unit]
	Description=nginx
	After=network.target
	  
	[Service]
	Type=forking
	ExecStart=/usr/local/nginx/sbin/nginx
	ExecReload=/usr/local/nginx/sbin/nginx -s reload
	ExecStop=/usr/local/nginx/sbin/nginx -s quit
	PrivateTmp=true
	  
	[Install]
	WantedBy=multi-user.target
	#########################################
	[Unit]:服务的说明
	Description:描述服务
	After:描述服务类别
	[Service]服务运行参数的设置
	Type=forking是后台运行的形式
	ExecStart为服务的具体运行命令
	ExecReload为重启命令
	ExecStop为停止命令
	PrivateTmp=True表示给服务分配独立的临时空间
	注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
	[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3
	
	开机自启:systemctl enable nginx.service
	查看状态:systemctl status nginx.service/sudo service nginx status

五:关于Django的静态文件

DEBUG = False

  1. 项目下新建static,staticfiles文件夹

  2. setting.py:

     STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
     STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
    
  3. url.py:

     from django.urls import path, re_path, include
     from django.conf.urls import url
     from django.contrib import admin
     from django.views import static
     from django.conf import settings
     urlpatterns = [
         #re_path(r'^admin/', admin.site.urls),
         #path('polls/', include('polls.urls')),
         url(r'^static/(?P<path>.*)$', static.serve,  {'document_root': settings.STATIC_ROOT}, name='static') 或
     ]
     urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT),
     urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)  
    
  4. 设置nginx

     cd /etc/nginx/conf/
     vim xx.conf
     
     将所有.conf文件中server下添加:
     
     location /static {  #这里做了访问静态目录不走uwsgi/gunicorn
     		expires 30d; # 可选
     		autoindex on; # 可选
     		add_header Cache-Control private; # 可选
     		alias /home/zyh/projects/mytestProject1/mysite/staticfiles/;(django setting中static_root对应)    		}
    
  5. 收集静态文件:

     python manage.py collectstatic 
     sudo service nginx restart # 重启nginx 
    

六:supervisor开机自启

  1. 配置系统文件

     cd /lib/systemd/system
     vim supervisord.service 
    
  2. 插入代码(可能已经自动添加了)

     [Unit]
     Description=Supervisord Service
    
     [Service]
     Type=forking
     ExecStart=/home/zyh/projects/mytestProject1/python3_venv/bin/supervisord -c /etc/supervisor/supervisord.conf
     ExecStop=/home/zyh/projects/mytestProject1/python3_venv/bin/supervisorctl $OPTIONS shutdown
     ExecReload=/home/zyh/projects/mytestProject1/python3_venv/bin/supervisorctl $OPTIONS reload
     KillMode=process
     Restart=on-failure
     RestartSec=42s
     
     [Install]
     WantedBy=multi-user.target
    
  3. 重新加载

     sudo systemctl daemon-reload
    
  4. 激活开机启动

     sudo systemctl enable supervisord.service
    

七:常用命令

  1. 后台运行‘cmd’

     $ nohup ‘cmd’  
    
  2. 查看端口

     netstat -nlpt | grep 9090  
    
  3. 查看关键字

     ps -aux | grep gunicorn  
    
  4. kill 端口

     sudo fuser -k 8000/tcp
    

八:理解

客户通过nginx:8000端口提交请求,nginx将动态请求分给gunicorn:9000端口,gunicorn通过Django执行后台程序后返回response给nginx,再返回给客服端;将静态请求设置缓存。supervisor检测gunicorn是否一直处于运行状态。

General preferences pane

General preferences pane

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值