Nginx+Tornado+Python3.7.4部署Django HTTP应用

部署http协议的django应用可以简单使用Nginx+Tornado来部署到云服务器,本文使用的是阿里云ECS主机,Centos7.6操作系统。使用的Django版本为2.1.9,使用的Tornado版本为6.0.3。

准备工作

安装tornado框架 pip install tornado 然后把静态文件收集好,设置为production的settings

STATIC_ROOT = str(APPS_DIR.path("staticfiles"))
# https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/static/"
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [str(APPS_DIR.path("static"))]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

配置Nginx来代理静态文件

/etc/nginx/nginx.conf直接修改

upstream tornado-backend {
                #http请求转发到tornado服务
        server localhost:6001;
        server localhost:6002;
        server localhost:6003;
        server localhost:6004;
}

location / {
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_pass http://tornado-backend;
}

location /static/ {
    root /root/zhihu/zhihu/;
}

location /media/ {
    root /root/zhihu/zhihu/;
}

上面的**root /root/zhihu/zhihu/;**表示你的静态文件的根目录。

如果你使用root用户,注意要再nginx.conf文件的顶部设置user nginx root;否则会出现403错误

编写tornado服务器

根目录下创建TornadoServer.py文件


import os
import sys
from tornado.options import options, define
from django.core.wsgi import get_wsgi_application
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi


app_path = os.path.abspath(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)
)
sys.path.append(os.path.join(app_path, "zhihu"))


define('port', default=6000, type=int, help='run server')

def main():
    tornado.options.parse_command_line()
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production')
    wsgi_app = tornado.wsgi.WSGIContainer(get_wsgi_application())
    http_server = tornado.httpserver.HTTPServer(wsgi_app, xheaders=True)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
    main()

服务器上运行

进入虚拟环境

python3 Tornadoserver.py --port=6001
python3 Tornadoserver.py --port=6002
python3 Tornadoserver.py --port=6003
python3 Tornadoserver.py --port=6004

ctrl + z可以放在后台来执行,一条一条来。 jobs -l 查看当前的后台任务 bg 1 2 3 4 一次性执行这些任务 fg 1 使任务1到前台运行

此时重启nginx服务: systemctl restart nginx 部署成功!