在 Windows 上"稳定"部署 Django 的关键结论先给你:
Windows 可以稳定跑 Django,但前提是:不用 Linux 专用工具、不用 Gunicorn、用正确的进程模型。
下面给你一套 在 Windows 上长期稳定运行(生产可用)的标准方案 ,以及 明确不该用什么。
🧱 一、Windows 上的「稳定架构」(推荐)
✅ 标准组合(已在大量企业内网环境使用)
Nginx (Windows)
↓
Waitress(WSGI Server)
↓
Django
↓
PostgreSQL / SQL Server / MySQL
🚀 二、核心组件选择(为什么这样选)
❌ 不要用
| 组件 | 原因 |
|---|---|
| Gunicorn | 不支持 Windows |
| uWSGI | Windows 支持差 |
| supervisor | Linux 专用 |
| fork 多进程模型 | Windows 不支持 |
✅ 必须用
1️⃣ WSGI Server:Waitress(强烈推荐)
bash
pip install waitress
启动:
bash
waitress-serve --listen=0.0.0.0:8000 myproject.wsgi:application
优点:
- 官方支持 Windows
- 稳定
- 多线程
- 无 fork
2️⃣ Web Server:Nginx(Windows 版)
- 反向代理
- 静态文件
- HTTPS
🔐 三、生产级 Nginx 配置(Windows)
nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
sendfile on;
upstream django {
server 127.0.0.1:8000;
}
server {
listen 80;
server_name localhost;
location /static/ {
alias D:/django_project/static/;
}
location / {
proxy_pass http://django;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
}
🗂 四、Django 必须做的配置
1️⃣ 关闭 debug
python
DEBUG = False
2️⃣ 允许域名
python
ALLOWED_HOSTS = ['*'] # 或指定域名/IP
3️⃣ 静态文件
bash
python manage.py collectstatic
python
STATIC_ROOT = BASE_DIR / 'static'
4️⃣ 日志(Windows 必须注意)
python
LOGGING = {
'handlers': {
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'logs/app.log',
'maxBytes': 50*1024*1024,
'backupCount': 10,
'delay': True, # ⭐⭐⭐ Windows 必须
},
},
}
🧠 五、进程守护(Windows 的"Supervisor")
✅ 用 Windows 服务
方案 A:nssm(强烈推荐)
1️⃣ 下载
https://nssm.cc/
2️⃣ 安装服务:
bash
nssm install django
配置:
- Path:
D:\venv\Scripts\waitress-serve.exe - Arguments:
--listen=0.0.0.0:8000 myproject.wsgi:application - Startup directory:项目目录
3️⃣ 启动服务:
bash
nssm start django
✅ 方案 B:Windows Task Scheduler(不如 nssm)
🧪 六、数据库选择建议(Windows 友好)
| 数据库 | 建议 |
|---|---|
| PostgreSQL | ✅ 官方 Windows 支持 |
| SQL Server | ✅ 企业常用 |
| MySQL | ⚠️ 可以 |
| SQLite | ❌ 不适合生产 |
🐳 七、Docker(Windows 上也很稳)
如果你能接受 Docker:
Docker Desktop + Linux 容器 = 最稳定方案
yaml
services:
web:
image: python:3.11
command: waitress-serve myproject.wsgi:application
这是 最接近 Linux 生产环境的方式
❗ 八、常见坑(你一定要避开)
| 坑 | 说明 |
|---|---|
| 用 runserver | ❌ 开发用 |
| Gunicorn | ❌ Windows |
| 多进程写日志 | ❌ WinError 32 |
| logrotate | ❌ Linux 专用 |
| fork | ❌ Windows |
✅ 九、稳定性清单(上线前检查)
- DEBUG=False
- Waitress 启动
- Nginx 反代
- 静态文件 collectstatic
- 日志加 delay=True
- 用 nssm 注册服务
- 防火墙放行端口
- 数据库远程连接正常
🎯 总结一句话
Windows 稳定部署 Django 的黄金组合是:
Nginx + Waitress + Django + NSSM
如果你愿意,可以告诉我:
- Django 版本
- Python 版本
- 是否内网 / 是否要 HTTPS
- 是否多实例
我可以直接给你一套 "可复制上线"的完整部署脚本(含 Nginx + NSSM + Django 配置) 💪