下面是一个完整的指南,介绍如何在Ubuntu系统上使用Nginx和Gunicorn部署Django应用。
sudo apt update
sudo apt install nginx python3-pip python3-venv
cd /path/to/your/django/project
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt # 如果有requirements.txt
pip install django gunicorn
gunicorn --bind 0.0.0.0:8000 your_project.wsgi:application
如果一切正常,你应该能够通过http://your-server-ip:8000
访问你的Django应用。
sudo nano /etc/systemd/system/gunicorn.service
添加以下内容(根据你的项目路径修改):
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/your/django/project
ExecStart=/path/to/your/django/project/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/your/django/project/project.sock your_project.wsgi:application
[Install]
WantedBy=multi-user.target
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
sudo nano /etc/nginx/sites-available/your_project
添加以下内容:
server {
listen 80;
server_name your_domain.com www.your_domain.com; # 如果没有域名,使用服务器IP
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path/to/your/django/project;
}
location / {
include proxy_params;
proxy_pass http://unix:/path/to/your/django/project/project.sock;
}
}
sudo ln -s /etc/nginx/sites-available/your_project /etc/nginx/sites-enabled
sudo nginx -t # 测试配置是否正确
sudo systemctl restart nginx
在Django的settings.py中:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
然后运行:
python manage.py collectstatic
sudo ufw allow 'Nginx Full'
现在你应该可以通过服务器的IP地址或配置的域名访问你的Django应用了。
502 Bad Gateway错误:
sudo systemctl status gunicorn
sudo journalctl -u gunicorn
静态文件不加载:
STATIC_ROOT
设置正确collectstatic
命令权限问题:
sudo chown -R www-data:www-data /path/to/your/project
如需HTTPS支持,可以考虑使用Let's Encrypt和Certbot配置SSL证书。