Django_Nginx+gunicorn 服务部署

之前通过uwsgi 部署的,昨天查到还可以这样部署,遂用之。总的来说确实很简单。

当前部署环境是阿里云,centos

步骤:

1.安装依赖

这个没啥好说的

sudo yum install python3
sudo yum install nginx

2.安装pip

curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

3.安装gunicorn工具

sudo pip install gunicorn
sudo pip install gevent   # 这个是gunicorn运行的一种模式

说明:安装完以后,系统会提示"The scripts gunicorn and gunicorn_paster are installed in '/usr/local/python3/bin' which is not on PATH "

[root@iZm5e8ip0m748x62a7n6i4Z build]# pip uninstall gunicorn
Uninstalling gunicorn-19.9.0:
  Would remove:
    /usr/local/python3/bin/gunicorn
    /usr/local/python3/bin/gunicorn_paster
    /usr/local/python3/lib/python3.6/site-packages/gunicorn-19.9.0.dist-info/*
    /usr/local/python3/lib/python3.6/site-packages/gunicorn/*
Proceed (y/n)? y
  Successfully uninstalled gunicorn-19.9.0
[root@iZm5e8ip0m748x62a7n6i4Z build]# pip install gunicorn
Looking in indexes: http://mirrors.aliyun.com/pypi/simple/
Collecting gunicorn
  Downloading http://mirrors.aliyun.com/pypi/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl (112kB)
    100% |████████████████████████████████| 122kB 2.2MB/s 
Installing collected packages: gunicorn
  The scripts gunicorn and gunicorn_paster are installed in '/usr/local/python3/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed gunicorn-19.9.0

此时需要将gunicorn 添加到环境变量中,2种永久方式添加,一个是

vim /etc/profile  #对所有用户生效
# 新增一行
export PATH=$PATH:/usr/local/python3/bin

另一个是,

vim ~/.bash_profile  # 对当前用户生效
# 新增一行
export PATH=$PATH:/usr/local/python3/bin

修改完文件后,重新登录系统即可生效。

但是我的账号有问题,增加了不生效,索性在启动脚本中每次增加。

4.配置nginx

  • 配置nginx.conf
worker_processes 1;
events {
    worker_connections 1024;
}
http {
    include       mime.types;   # 这个规定了静态文件的类型,很重要,不然样式没法生效
    sendfile on;
    gzip              on;
    gzip_http_version 1.0;
    gzip_proxied      any;
    gzip_min_length   500;
    gzip_disable      "MSIE [1-6]\.";
    gzip_types        text/plain text/xml text/css
                      text/comma-separated-values
                      text/javascript
                      application/x-javascript
                      application/atom+xml;
    include /etc/nginx/sites-available/*.conf;
}
  • 配置你自己定义的服务server
    路径:/etc/nginx/sites-available/exmple.conf;
server {
    listen 80;
    server_name  build.2222.com;
    charset utf-8;
    client_max_body_size 200m;
    access_log  /var/log/nginx/build-access.log;
    error_log  /var/log/nginx/build-err.log;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        #静态文件如js,css的存放目录
        alias /home/build/build/static/;
    }
    location / {
        proxy_pass http://0.0.0.0:8000; # 这里要配合启动文件使用
        proxy_redirect     off;
        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;
    }
}
# 重启nginx 
/etc/init.d/nginx restart   或者  nginx -s reload

5.开发环境迁移项目

如果从开发环境迁移项目,则会涉及到很多依赖,所以这时候需要一个将依赖库同步部署到新服务器上。
方法:

sudo pip freeze >requirements.txt
# 此时项目根目录会生成一个requirements.txt文件
  • 然后在服务器执行:
sudo pip install -r requirements.txt

则完成了项目迁移
至此基础依赖都完事了。然后就是启动服务即可。

6.启动

6.1 项目根目录新建gunicorn配置文件

#gunicorn.py
# coding:utf-8
__author__ = 'xcma'
import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import os
import multiprocessing
bind = '0.0.0.0:8000'      #绑定ip和端口号
backlog = 512                #监听队列
chdir = '/home/build/build'  #gunicorn要切换到的目的工作目录
timeout = 30      #超时
worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式

workers = multiprocessing.cpu_count() * 2 + 1    #进程数
threads = 2 #指定每个进程开启的线程数
loglevel = 'info' #日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'    #设置gunicorn访问日志格式,错误日志无法设置

"""
其每个选项的含义如下:
h          remote address
l          '-'
u          currently '-', may be user name in future releases
t          date of the request
r          status line (e.g. ``GET / HTTP/1.1``)
s          status
b          response length or '-'
f          referer
a          user agent
T          request time in seconds
D          request time in microseconds
L          request time in decimal seconds
p          process ID
"""
accesslog = "/home/log/gunicorn_access.log"      #访问日志文件
errorlog = "/home/log/gunicorn_error.log"        #错误日志文件

6.2 配置django的settting文件

# 在setting中新增app,这个app在ide中会报错,不用管。
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'appack',
    'api',
    'gunicorn'
]

6.3 启动脚本

  • restart.sh
#!/bin/sh
## service name
#项目的目录
SERVICE_DIR=/home/build/build
#gunicorn的名字
SERVICE_NAME=gunicorn
#gunicorn的配置文件名
SERVICE_CONF=gunicon.py
#pid存放的位置
PID=gunicorn\.pid
export PATH=$PATH:/usr/local/python3/bin
cd $SERVICE_DIR
git checkout . && git clean -xdf
git pull

start(){
       nohup gunicorn build.wsgi:application -c $SERVICE_DIR/$SERVICE_CONF >/dev/null 2>&1 &
       echo $! > $SERVICE_DIR/$PID
       echo "*** start $SERVICE_NAME ***"
}
stop(){
       kill `cat $SERVICE_DIR/$PID`
       rm -rf $SERVICE_DIR/$PID
       echo "*** stop $SERVICE_NAME ***"

       sleep 2
       P_ID=`ps -ef | grep -w "$SERVICE_NAME" | grep -v "grep" | awk '{print $2}'`
       if [ "$P_ID" == "" ]; then
           echo "*** $SERVICE_NAME process not exists or stop success ***"
       else
           echo "*** $SERVICE_NAME process pid is:$P_ID ***"
           echo "*** begin kill $SERVICE_NAME process,kill is:$P_ID ***"
           kill -9 $P_ID
       fi
}
f_usage() {
   echo "USAGE: restart [options]"
   echo "OPTIONS:"
   echo "       start"
   echo "       stop "
   echo "       restart"
}
case "$1" in

   "start")
       start
       ;;
   "stop")
       stop
       ;;
   "restart")
       stop
       sleep 2
       start
       echo "*** restart $SERVICE_NAME ***"
       ;;
   *)
   f_usage
   ;;

esac
exit 0

6.3 用脚本启动:

 sh restart.sh restart
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容

  • 望峰楼 迷路上~~~ 难得的合照 大大大合照
    吴秀兰阅读 275评论 0 0
  • 因为逝者已去,或许我们永远无法知道真相是什么,所以我以下的思考仅基于网络上已知的关于该案一些描述。 首先,关于善良...
    sayaga阅读 514评论 0 0
  • Why WAIT TO BE GREAT Chapter1 There Are Only Two Times in...
    伊枝杪阅读 296评论 3 6
  • 从人类诞生,就有了他们,他们追求黑暗,就像人类渴望光明,他们和人类轮流主宰这个世界,12小时一个换班,“鬼”——这...
    艾迪蓝波阅读 1,620评论 0 55