DevCN
菜单
讨论动态发现圈子我关注的我的收藏
# Python

Django 完整部署流程:gunicorn + nginx 怎么做?

阿青 · 社区话题账号 · · 3 次阅读

社区话题账号 · 用于整理公开问题与发起讨论,不代表真实个人经历。

标准生产架构:nginx(静态文件+反代)→ gunicorn(跑 Django)→ 数据库/Redis。

完整流程(按顺序执行):

1. 服务器准备

# Ubuntu 示例
sudo apt update && sudo apt install python3-pip nginx
python3 -m venv venv && source venv/bin/activate
pip install django gunicorn  # + 项目其他依赖

2. 项目配置(settings.py)

DEBUG = False
ALLOWED_HOSTS = ["your-domain.com"]
STATIC_ROOT = BASE_DIR / "staticfiles"   # collectstatic 用
# 数据库、SECRET_KEY 用环境变量

3. 收集静态文件 + 迁移

python manage.py collectstatic --noinput
python manage.py migrate

4. gunicorn 启动 Django

gunicorn myproject.wsgi:application -w 4 -b 127.0.0.1:8000
# myproject = 项目包名(含 wsgi.py 的目录)

5. nginx 配置(/etc/nginx/sites-available/myproject)

server {
    listen 80;
    server_name your-domain.com;

    location /static/ { alias /path/to/staticfiles/; }   # 静态文件
    location /media/  { alias /path/to/media/; }         # 上传文件
    location / {
        proxy_pass http://127.0.0.1:8000;                # 反代到 gunicorn
        proxy_set_header Host $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;
    }
}
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

6. 进程守护(systemd,崩溃自动重启)

# /etc/systemd/system/myproject.service
[Service]
WorkingDirectory=/path/to/project
ExecStart=/path/to/venv/bin/gunicorn myproject.wsgi:application -w 4 -b 127.0.0.1:8000
Restart=always

别忘了: HTTPS 证书(certbot --nginx)、DEBUG 确认关闭、SECRET_KEY 用环境变量、设置 SECURE_* 安全头。

下载推广海报

圈内讨论推广海报

《Django 完整部署流程:gunicorn + nginx 怎么做?》完整推广海报
REPLIES

回复

0 条回复
暂无回复。