插件窝 干货文章 Django怎么部署

Django怎么部署

myproject Gunicorn 部署 Nginx 877    来源:    2025-04-23

Django 项目部署指南

Django 是一个流行的 Python Web 框架,以下是几种常见的部署方式:

1. 传统服务器部署 (Linux + Nginx + Gunicorn/uWSGI)

基本步骤:

  1. 准备服务器

    • 安装 Python 3.x
    • 安装 pip
    • 安装虚拟环境工具:pip install virtualenv
  2. 设置项目环境

    mkdir /var/www/myproject
    cd /var/www/myproject
    virtualenv venv
    source venv/bin/activate
    pip install django gunicorn
    
  3. 配置 Gunicorn

    • 创建 gunicorn.service 文件 (Systemd 服务)
    [Unit]
    Description=gunicorn daemon
    After=network.target
    
    [Service]
    User=www-data
    Group=www-data
    WorkingDirectory=/var/www/myproject
    ExecStart=/var/www/myproject/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/www/myproject/myproject.sock myproject.wsgi:application
    
    [Install]
    WantedBy=multi-user.target
    
  4. 配置 Nginx

    server {
       listen 80;
       server_name yourdomain.com;
    
       location = /favicon.ico { access_log off; log_not_found off; }
       location /static/ {
           root /var/www/myproject;
       }
    
       location / {
           include proxy_params;
           proxy_pass http://unix:/var/www/myproject/myproject.sock;
       }
    }
    
  5. 启动服务

    sudo systemctl start gunicorn
    sudo systemctl enable gunicorn
    sudo systemctl restart nginx
    

2. 使用 Docker 部署

  1. 创建 Dockerfile

    FROM python:3.9
    ENV PYTHONUNBUFFERED 1
    RUN mkdir /code
    WORKDIR /code
    COPY requirements.txt /code/
    RUN pip install -r requirements.txt
    COPY . /code/
    
  2. docker-compose.yml 示例

    version: '3'
    
    services:
     web:
       build: .
       command: gunicorn myproject.wsgi:application --bind 0.0.0.0:8000
       volumes:
         - .:/code
       ports:
         - "8000:8000"
     nginx:
       image: nginx:latest
       ports:
         - "80:80"
       volumes:
         - ./nginx.conf:/etc/nginx/conf.d/default.conf
         - ./static:/code/static
       depends_on:
         - web
    

3. 云平台部署

Heroku 部署

  1. 安装 Heroku CLI
  2. 创建 Procfile web: gunicorn myproject.wsgi --log-file -
  3. 部署命令 bash heroku create git push heroku master heroku run python manage.py migrate

AWS Elastic Beanstalk

  1. 安装 EB CLI
  2. 初始化 EB bash eb init -p python-3.8 django-app eb create django-env

4. 部署前检查清单

  1. 设置 DEBUG = False
  2. 配置 ALLOWED_HOSTS
  3. 设置静态文件 (STATIC_ROOTcollectstatic)
  4. 配置数据库 (生产环境不要用 SQLite)
  5. 设置安全密钥 (不要硬编码在代码中)
  6. 配置 HTTPS (使用 Let's Encrypt 免费证书)
  7. 设置日志记录
  8. 考虑使用 WhiteNoise 简化静态文件服务

性能优化建议

  1. 使用缓存 (Redis/Memcached)
  2. 启用数据库连接池
  3. 使用 CDN 分发静态文件
  4. 优化数据库查询
  5. 考虑异步任务 (Celery)

希望这些信息对您有帮助!根据您的具体需求选择最适合的部署方式。