Python Web应用部署方式:Django+Gunicorn+Gevent+nohup+Nginx

前期准备

更新apt-get

apt-get update

安装pip

sudo apt-get install python-pip

安装Django Gunicorn Gevent

gunicorn:高性能WSGI服务器;

gevent:把Python同步代码变成异步协程的库;

sudo pip install django gunicorn gevent

确保安装Nginx,及server最简配置

server {
        listen   80;
        server_name 服务器ip;
        access_log  /var/log/nginx/access.log;

        location / {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

以上是最简单的Nginx配置,目的是为能跑起来就行,更多其他详细配置还请参照其他文章。

启动

Gunicorn方式

Gunicorn:一个开源Python WSGI UNIX的HTTP服务器,Github仓库地址在这,传说速度快(配置快、运行快)、简单,默认是同步工作,支持Gevent、Eventlet异步,支持Tornado,官方有很详细的文档可以参阅。

需要在你的Django项目的settings.py中的INSTALLED_APPS加入:gunicorn

INSTALLED_APPS = [
    ...
    ...
    'gunicorn',  # 部署用
]
Gunicorn启动语法:gunicorn --worker-class=gevent 项目名.wsgi:application
  • –worker-class 指定工作方式,这里我用的gevent 如果提示You need gevent installed to use this worker则表示你还没有安装 gevent。
  • 项目名.wsgi:application 这里是需要指定django的项目名,你找到wsgi文件,就知道项目名是什么了,wsgi文件就是在Django创建项目的时候会自动生成对应名字文件夹中的wsgi.py。

nohup方式

nohup是一个 Linux 命令,搭配 & 来不挂断地运行某条命令达到后台执行的效果,默认会在根目录生成一个 nohup.out 文件用来记录所有的 log 信息,也可以重定向到其他位置。这里我们用它来执行gunicorn,来保持 gunicorn 进程不会被挂断。

不使用gunicorn配置文件(需进入项目目录)

nohup gunicorn --worker-class=gevent 项目名.wsgi:application -b 127.0.0.1:8000&

  • –worker-class来指定工作方式为gevent,-b指定地址和端口号。
  • 在尾部加上&(and)字符表示后台运行
  • 执行这条命令后可以用ps命令查看进程,就能看到gunicorn了

使用配置文件方式

gunicorn.conf.py:
import multiprocessing

bind = "127.0.0.1:8000"   #绑定的ip与端口
workers = 4                #进程数
errorlog = '/home/xxx/xxx/gunicorn.error.log' #发生错误时log的路径
accesslog = '/home/xxx/xxx/gunicorn.access.log' #正常时的log路径
#loglevel = 'debug'   #日志等级
proc_name = 'gunicorn_project'   #进程名
nohup gunicorn --worker-class=gevent 项目名.wsgi:application -c /home/xxx/xxx/gunicorn.conf.py& 


supervisor方式


supervisord.conf :


[program:项目名]
autorestart=true
command= 这里写上面gunicorn 的command
directory= 网站所在的目录
process_name= top 中显示的进程名
redirect_stderr=true
stdot_logfile=log文件

启动supervisor 用命令

  • supervisord -c/etc/supervisor/supervisord.conf

关闭supervisor 用命令

  • supervisorctlshutdown

如果先建的djangoblog.conf(控制文件),在使用启动命令后这些经过配置的程序也会启动

启动程序

  • supervisorctl start program_name

这里的program的name是配置文件ini中的[program:name],所以这里的program_name是djangoblog

关闭程序

  • supervisorctl stop program_name

刷新配置文件 如果启动后,修改了ini文件,可以通过reload命令来刷新

  • supervisorctl reload

查看supervisor的运行状态

  • ps-efH|grepsupervisor

Start

好了,以上就是整个服务器的配置了。然后我们重启下Nginx,刷新页面就能看到你的Django App了。

sudo service nginx restart