义乌市纤凝网

Nginx+uWSGI部署实践

2026-04-04 15:52:02 浏览次数:1
详细信息

一、部署架构概述

用户请求 → Nginx (反向代理) → uWSGI (应用服务器) → Django/Flask应用

二、环境准备

1. 安装必要软件包

# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip python3-venv nginx

# CentOS/RHEL
sudo yum install python3 python3-pip nginx

2. 创建Python虚拟环境

mkdir /var/www/myapp
cd /var/www/myapp
python3 -m venv venv
source venv/bin/activate
pip install uwsgi django  # 或 Flask

三、uWSGI配置

1. 基本配置文件 uwsgi.ini

[uwsgi]
# 项目目录
chdir = /var/www/myapp
# 加载WSGI模块
module = myproject.wsgi:application  # Django
# module = app:app  # Flask

# 虚拟环境
home = /var/www/myapp/venv

# uWSGI运行参数
master = true
processes = 4
threads = 2
enable-threads = true

# socket文件位置(用于与Nginx通信)
socket = /var/www/myapp/uwsgi.sock
# 或者使用TCP端口
# socket = 127.0.0.1:8000

# 权限设置
chmod-socket = 660
uid = www-data
gid = www-data

# 日志文件
logto = /var/log/uwsgi/myapp.log
log-maxsize = 10000000  # 10MB

2. Systemd服务配置 /etc/systemd/system/uwsgi.service

[Unit]
Description=uWSGI Emperor
After=syslog.target

[Service]
ExecStart=/var/www/myapp/venv/bin/uwsgi --ini /var/www/myapp/uwsgi.ini
User=www-data
Group=www-data
WorkingDirectory=/var/www/myapp
Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all

[Install]
WantedBy=multi-user.target

3. 管理uWSGI服务

# 启动服务
sudo systemctl start uwsgi

# 设置开机启动
sudo systemctl enable uwsgi

# 查看状态
sudo systemctl status uwsgi

# 重启服务
sudo systemctl restart uwsgi

四、Nginx配置

1. 站点配置文件 /etc/nginx/sites-available/myapp

upstream django {
    server unix:///var/www/myapp/uwsgi.sock;
    # 如果是TCP端口
    # server 127.0.0.1:8000;
}

server {
    listen 80;
    server_name example.com www.example.com;

    # 静态文件处理
    location /static/ {
        alias /var/www/myapp/static/;
        expires 30d;
        access_log off;
    }

    location /media/ {
        alias /var/www/myapp/media/;
        expires 30d;
        access_log off;
    }

    # 动态请求转发到uWSGI
    location / {
        include uwsgi_params;
        uwsgi_pass django;

        # 超时设置
        uwsgi_read_timeout 300s;
        uwsgi_send_timeout 300s;
        uwsgi_connect_timeout 75s;

        # 缓冲区设置
        uwsgi_buffer_size 8k;
        uwsgi_buffers 256 8k;
        uwsgi_busy_buffers_size 64k;
        uwsgi_temp_file_write_size 256k;

        # 禁用缓冲
        uwsgi_buffering off;

        # 传递真实IP
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # 启用gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript 
               application/javascript application/xml+rss 
               application/json;
}

2. 启用站点配置

# 创建符号链接
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/

# 测试配置
sudo nginx -t

# 重启Nginx
sudo systemctl restart nginx

五、应用部署示例

1. Django项目配置

# 收集静态文件
python manage.py collectstatic --noinput

# 数据库迁移
python manage.py migrate

# 修改settings.py
ALLOWED_HOSTS = ['example.com', 'localhost', '127.0.0.1']
STATIC_ROOT = '/var/www/myapp/static'

2. Flask项目配置

# app.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    app.run()

六、性能优化配置

1. 高级uWSGI配置

[uwsgi]
# 连接池设置
max-requests = 1000
max-requests-delta = 100
max-worker-lifetime = 3600
reload-on-as = 512
reload-on-rss = 192

# 异步支持(需要安装gevent/greenlet)
# async = 1000
# gevent = 1000

# 内存优化
limit-as = 512  # 限制内存使用
reload-on-rss = 200  # 内存达到200MB时重启worker

# 优雅重启
lazy-apps = true
cheaper-algo = spare
cheaper = 2
cheaper-initial = 4
workers = 8
cheaper-step = 1

2. Nginx优化配置

# /etc/nginx/nginx.conf 中的部分优化
worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 2048;
    multi_accept on;
    use epoll;
}

http {
    # 缓存设置
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m 
                     max_size=1g inactive=60m use_temp_path=off;

    # 连接优化
    keepalive_timeout 30;
    keepalive_requests 100;
}

七、监控与调试

1. 日志配置

# uWSGI日志配置
logto = /var/log/uwsgi/myapp-%Y-%m-%d.log
log-format = %(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size) "%(referer)" "%(uagent)"
log-slow = 3000  # 记录超过3秒的请求
log-5xx = true   # 记录5xx错误

2. 监控脚本

#!/bin/bash
# check_uwsgi_status.sh

# 检查uWSGI进程
if ! pgrep -f "uwsgi.*myapp" > /dev/null; then
    echo "uWSGI is not running!"
    systemctl restart uwsgi
fi

# 检查socket文件
if [ ! -S "/var/www/myapp/uwsgi.sock" ]; then
    echo "Socket file missing!"
    systemctl restart uwsgi
fi

3. 常用调试命令

# 查看uWSGI日志
tail -f /var/log/uwsgi/myapp.log

# 检查socket连接
ss -lnp | grep uwsgi

# 测试uWSGI
curl -I http://localhost:8000

# 查看进程状态
ps aux | grep uwsgi

八、SSL/TLS配置(HTTPS)

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    # SSL优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 其他配置与HTTP相同
    location / {
        include uwsgi_params;
        uwsgi_pass django;
    }
}

# HTTP重定向到HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

九、常见问题解决

1. 502 Bad Gateway

# 检查socket权限
sudo chown www-data:www-data /var/www/myapp/uwsgi.sock

# 检查uWSGI进程
sudo systemctl status uwsgi

# 查看错误日志
sudo journalctl -u uwsgi --no-pager -n 50

2. 静态文件无法访问

# 检查文件权限
sudo chown -R www-data:www-data /var/www/myapp/static
sudo chmod -R 755 /var/www/myapp/static

# 检查Nginx配置中的alias路径

3. 性能问题优化

十、一键部署脚本示例

#!/bin/bash
# deploy.sh

set -e

APP_NAME="myapp"
APP_DIR="/var/www/$APP_NAME"
VENV_DIR="$APP_DIR/venv"

echo "开始部署 $APP_NAME..."

# 1. 创建目录
sudo mkdir -p $APP_DIR
sudo chown -R $USER:$USER $APP_DIR

# 2. 设置Python虚拟环境
cd $APP_DIR
python3 -m venv venv
source venv/bin/activate

# 3. 安装依赖
pip install --upgrade pip
pip install uwsgi django gunicorn

# 4. 创建uWSGI配置
cat > $APP_DIR/uwsgi.ini << EOF
[uwsgi]
chdir = $APP_DIR
module = myproject.wsgi:application
home = $VENV_DIR
master = true
processes = 4
socket = $APP_DIR/uwsgi.sock
chmod-socket = 660
vacuum = true
EOF

# 5. 启动服务
sudo systemctl daemon-reload
sudo systemctl start uwsgi
sudo systemctl enable uwsgi

echo "部署完成!"

这个实践指南涵盖了从基础部署到生产环境优化的完整流程,您可以根据具体项目需求进行调整。

相关推荐