在开始配置前,请确保已安装以下组件: - Python环境(推荐3.6+) - Nginx - uWSGI - 虚拟环境(可选但推荐)
pip install uwsgi
# Ubuntu/Debian
sudo apt-get install nginx
# CentOS/RHEL
sudo yum install nginx
假设你的Python Web项目结构如下:
/mywebapp
├── app.py # 主应用文件
├── requirements.txt # 依赖文件
├── static/ # 静态文件
└── templates/ # 模板文件
mywebapp_uwsgi.ini
)[uwsgi]
# 应用相关配置
module = app:app # 对于Flask应用,如果是其他框架请相应调整
callable = app # Flask应用对象名称
# 进程和线程配置
master = true
processes = 4
threads = 2
# 日志配置
logto = /var/log/uwsgi/mywebapp.log
log-reopen = true
# 套接字配置
socket = /tmp/mywebapp.sock
chmod-socket = 660
vacuum = true
# 虚拟环境(如果使用)
# virtualenv = /path/to/venv
uwsgi --ini mywebapp_uwsgi.ini
/etc/nginx/sites-available/mywebapp
)server {
listen 80;
server_name yourdomain.com; # 替换为你的域名或IP
location / {
include uwsgi_params;
uwsgi_pass unix:/tmp/mywebapp.sock;
}
location /static {
alias /path/to/your/mywebapp/static;
}
# 错误日志
error_log /var/log/nginx/mywebapp_error.log;
access_log /var/log/nginx/mywebapp_access.log;
}
sudo ln -s /etc/nginx/sites-available/mywebapp /etc/nginx/sites-enabled
sudo nginx -t # 测试配置
sudo systemctl restart nginx
/etc/systemd/system/mywebapp.service
)[Unit]
Description=uWSGI instance to serve mywebapp
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/your/mywebapp
ExecStart=/usr/local/bin/uwsgi --ini /path/to/your/mywebapp_uwsgi.ini
[Install]
WantedBy=multi-user.target
sudo systemctl start mywebapp
sudo systemctl enable mywebapp
权限问题:
sudo chown www-data:www-data /tmp/mywebapp.sock
502 Bad Gateway:
/var/log/nginx/error.log
静态文件不加载:
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 其他配置与之前相同
}
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
upstream mywebapp {
server unix:/tmp/mywebapp.sock;
server unix:/tmp/mywebapp2.sock;
}
server {
location / {
uwsgi_pass mywebapp;
# 其他配置
}
}
通过以上步骤,你应该能够成功配置Nginx和uWSGI来部署你的Python Web项目。根据你的具体框架(Flask、Django等),可能需要进行一些微调。