在Linux主机上,使用gunicorn部署django应用

0
(0)

gunicorn全称是 Green Unicorn,是一种Python WSGI HTTP Server,常用来托管django , flask等应用。

django本身具体web服务的能力,比如使用命令:

python manage.py runserver 127.0.0.1:8000

但是,这样运行仅支持一个工作进程,如果需要以多个进程运行django应用,就要使用wsgi服务来托管,gunicorn就是比较常用的选择。

一、安装:

pip install gunicorn

二、基本命令:

gunicorn [OPTIONS] APP_MODULE

三、部署django应用的配置文件:

gunicorn有许多命令行参数,但一般做法是在项目的根目录创建配置文件,配置文件 gunicorn.conf.py示例如下:

# 绑定的端口
bind = "127.0.0.1:8000"
# workers是工作线程数,根据文档推荐,一般设置成:服务器CPU个数 + 1,具体使用以实际为准
workers = 3
# 是否以后台运行, 注意参数值使用了单引号
daemon = 'true'
# 错误日志的路径
errorlog = './logs/gunicorn.error.log'
# 请求日志的路径
accesslog = './logs/gunicorn.access.log'
# 日志等级
loglevel = 'info'
# 其他参数可参考官方文档

四、启动应用, 比如:

cd [项目目录]
gunicorn -c gunicorn.conf.py myproject.wsgi

其中 -c gunicorn.conf.py是指定配置文件, myproject.wsgi是django的WSGI模块,在创建项目时由django-admin命令自动生成

启动程序后,可以在浏览器中,使用 http://127.0.0.1:8000访问django项目了。

如果需要将应用配置成服务,可以使用supervisor或者systemd等服务进程管理工具。 supervisor是一个比较经典的进程管理工具,网上也有很多supervisor+nginx+gunicorn部署django的文章,但是supervisor还是需要使用systemd(目前主流的linux系统都支持systemd)来托管,具体方法本文略。

所以,不如直接用systemd托管gunicorn, 具体方式为:

一、创建一个 gunicorn.service文件

[Unit]
Description=gunicorn application
After=network.target

[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/path/to/djangoproject
ExecStart=/path/to/gunicorn -c /path/to/djangoproject/gunicorn.conf.py myproject.wsgi

[Install]
WantedBy=multi-user.target

二、将编辑好的文件复制到 /etc/systemd/system/ 目录下

三、使用以下命令管理gunicorn服务:

sudo systemctl start gunicorn
sudo systemctl enable gunicorn
sudo systemctl status gunicorn

如果需要对应用做更多的控制,比如托管静态资源文件,SSL证书,开启gzip,开启浏览器缓存等,还可以搭配nginx使用。

一、安装nginx

1.ubuntu:

apt update
apt install nginx

2.centos/redhat:

yum install nginx

3.下载源码后编译安装,适用需要于对nginx定制的场景

二、创建一个nginx配置文件 gunicorn.conf,并放到 /etc/nginx/conf.d/目录下。如果是编译安装的nginx,则要放到相应的目录下

server {
    listen 80;
    # listen 443 ssl;
    server_name cnanyi.cn;
    # 证书配置
    # 请求路径配置
    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;
    }
    # 如果需要托管static
    location /static/ {
        index index.html;
        alias /path/to/static;
    }
}

三、验证文件:

nginx -t

如果语法有错误,以上命令会提示错误位置和信息

四、启动服务

sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx

2025/9/18 于 北京 回龙观 东大街

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注