Nginx反向代理WebSocket配置笔记

1. WebSocket协议简介

WebSocket是一种在单个TCP连接上进行全双工通信的协议,允许服务端主动向客户端推送数据。

2. Nginx配置WebSocket反向代理

基本配置

bash 复制代码
http {
    upstream websocket_backend {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }
    
    server {
        listen 80;
        server_name example.com;
        
        location /websocket/ {
            # 核心代理配置
            proxy_pass http://websocket_backend;
            
            # WebSocket必需的头信息
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            
            # 其他重要配置
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            # 超时设置
            proxy_read_timeout 3600s;
            proxy_send_timeout 3600s;
            proxy_connect_timeout 30s;
        }
    }
}

详细配置说明

必需的头信息配置
bash 复制代码
# 升级HTTP协议到WebSocket
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
超时配置优化
bash 复制代码
# WebSocket连接需要较长的超时时间
proxy_read_timeout 3600s;    # 读取超时
proxy_send_timeout 3600s;    # 发送超时
proxy_connect_timeout 30s;   # 连接超时
负载均衡配置
bash 复制代码
upstream websocket_cluster {
    # 负载均衡算法
    ip_hash;  # 保持会话粘性
    
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 weight=1;
    
    # 健康检查
    check interval=3000 rise=2 fall=5 timeout=1000;
}

3. 完整配置示例

单服务器配置

bash 复制代码
server {
    listen 443 ssl;
    server_name websocket.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/private.key;
    
    location /ws {
        proxy_pass http://localhost:3000;
        
        # WebSocket升级头
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        
        # 客户端真实信息
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 缓冲区设置
        proxy_buffering off;
        
        # 超时设置
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
        proxy_connect_timeout 30s;
    }
}

多服务器负载均衡

bash 复制代码
upstream websocket_servers {
    ip_hash;
    server 10.0.1.10:8080;
    server 10.0.1.11:8080;
    server 10.0.1.12:8080;
}

server {
    listen 80;
    server_name ws.example.com;
    
    location / {
        proxy_pass http://websocket_servers;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        
        # 重要:禁用缓冲区
        proxy_buffering off;
        
        # 长连接超时
        proxy_read_timeout 3600s;
    }
}

4. 高级配置选项

连接数限制

bash 复制代码
location /websocket/ {
    # 限制并发连接数
    limit_conn websocket_zone 10;
    
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

# 定义连接限制区域
limit_conn_zone $binary_remote_addr zone=websocket_zone:10m;

SSL/TLS配置

bash 复制代码
server {
    listen 443 ssl http2;
    server_name websocket.example.com;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # WebSocket over WSS
    location /wss {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

5. 常见问题排查

连接断开问题

bash 复制代码
# 增加超时时间
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;

# 保持连接活跃
proxy_set_header Connection "keep-alive, upgrade";

代理缓冲区问题

bash 复制代码
location /websocket/ {
    # 禁用缓冲区确保实时通信
    proxy_buffering off;
    proxy_buffer_size 16k;
    
    proxy_pass http://backend;
    # ... 其他配置
}

6. 性能优化建议

  1. 使用HTTP/2:提高连接效率

  2. 启用Gzip压缩:压缩文本数据

  3. 调整缓冲区大小:根据消息大小调整

  4. 使用keepalive连接:减少连接建立开销

  5. 监控连接状态:及时发现问题

7. 测试验证

使用简单的HTML页面测试WebSocket连接:

html 复制代码
<!DOCTYPE html>
<html>
<body>
<script>
const ws = new WebSocket('wss://websocket.example.com/ws');
ws.onopen = () => console.log('Connected');
ws.onmessage = (event) => console.log('Received:', event.data);
ws.onclose = () => console.log('Disconnected');
</script>
</body>
</html>

总结

Nginx作为WebSocket反向代理时,关键在于正确配置HTTP协议升级头和适当的超时设置。通过合理的负载均衡和性能调优,可以构建稳定高效的WebSocket服务架构。

相关推荐
fangzhanpeng1681 天前
快速掌握C#语言基础知识点(1.基础数据类型)
开发语言·c#·1024程序员节
无己心3 天前
面向多平台 AI 搜索引擎的适配层架构设计
前端·人工智能·搜索引擎·ai·1024程序员节
u0103055279 天前
AI驱动的安卓UI自动生成功能实现
人工智能·1024程序员节
u01030552710 天前
长株潭智能体赋能腾讯元器链接共享
1024程序员节
云贝贝贝11 天前
OceanBase认证体系介绍与备考指南
运维·服务器·oceanbase·1024程序员节
u01030552711 天前
Java图像处理实战指南
人工智能·1024程序员节
u01030552712 天前
Java AWT鼠标事件全解析
人工智能·1024程序员节
u01030552714 天前
Java实用类应用精讲
人工智能·1024程序员节
u01030552714 天前
Java I/O核心操作实战
人工智能·1024程序员节
u01030552715 天前
ArrayList操作详解与实战应用
人工智能·1024程序员节