nginx 代理tcp端口
				
									
					
					
						 | 
						
							
							admin 
							
							
								2025年6月30日 18:9
								本文热度 2298
							
							 
						 | 
					
					
				 
				应用场景,我们由于网络限制,只有前置机或者固定服务器可以与外部链接, 要使用 Nginx 代理 TCP 端口(如数据库、SSH、游戏服务器等非 HTTP 服务),需使用 Nginx Stream 模块。该模块专门处理 TCP/UDP 流量,配置与 HTTP 代理有所不同。以下是详细配置步骤:
一、确认 Nginx 是否支持 Stream 模块
- 检查编译参数:
nginx -V 2>&1 | grep stream
 - 若输出包含 
--with-stream,说明已启用 Stream 模块。 - 若未启用,需重新编译 Nginx 并添加 
--with-stream 参数(或使用包含该模块的发行版,如 Ubuntu 的 nginx-extras)。 
二、配置 TCP 代理(示例:代理 MySQL 端口 3306)
1. 创建 Stream 配置文件
在 Nginx 配置目录(通常为 /etc/nginx)下创建 stream.conf:
# /etc/nginx/stream.conf
stream {
    # 定义日志格式(可选)
    log_format tcp '$remote_addr [$time_local] '
                   '$protocol $status $bytes_sent $bytes_received '
                   '$session_time "$upstream_addr" '
                   '"$upstream_bytes_sent" "$upstream_bytes_received"';
    access_log /var/log/nginx/tcp_access.log tcp;
    error_log /var/log/nginx/tcp_error.log;
    # TCP 代理配置(监听 63306 端口,转发到后端 MySQL 3306)
    server {
        listen 63306;  # 代理服务器监听端口
        proxy_pass 192.168.1.100:3306;  # 后端真实服务器地址:端口
        # 可选参数
        proxy_connect_timeout 10s;       # 连接超时时间
        proxy_timeout 300s;             # 会话超时时间
        proxy_buffer_size 16k;          # 缓冲区大小
    }
}
2. 在主配置文件中引入 Stream 配置
编辑 /etc/nginx/nginx.conf,在文件末尾添加:
# /etc/nginx/nginx.conf
include /etc/nginx/stream.conf;
三、多端口代理配置示例
若需同时代理多个 TCP 服务(如 MySQL 和 Redis),可在 stream.conf 中添加多个 server 块:
stream {
    # MySQL 代理
    server {
        listen 63306;
        proxy_pass 192.168.1.100:3306;
    }
    # Redis 代理
    server {
        listen 6379;
        proxy_pass 192.168.1.101:6379;
    }
    # SSH 代理
    server {
        listen 2222;
        proxy_pass 192.168.1.102:22;
    }
}
四、常用 Stream 模块参数说明
 |  |  | 
|---|
listen |  | 63306 | 
proxy_pass |  | 192.168.1.100:3306 | 
proxy_connect_timeout |  | 10s | 
proxy_timeout |  | 300s | 
proxy_buffer_size |  | 8k | 
ssl_preread | 启用 SSL/TLS 预读取(用于 SNI 路由) | on | 
五、验证配置并重启 Nginx
重启 Nginx:
systemctl restart nginx
验证代理是否生效:
# 检查端口监听
netstat -tulpn | grep nginx
# 使用 telnet 测试连接(以 MySQL 为例)
telnet localhost 63306
六、注意事项
- 示例(以 
firewalld 为例):firewall-cmd --add-port=63306/tcp --permanent
firewall-cmd --reload
 
- 高并发场景下,建议调整 
worker_processes 和 worker_connections 参数。 - 开启 
sendfile 提升传输效率:stream {
    sendfile on;
    # 其他配置...
}
 
- 通过 
tcp_access.log 和 tcp_error.log 监控代理流量。 - 使用 
nginx -s reload 热加载配置,避免中断服务。 
通过以上配置,Nginx 可高效代理各类 TCP 服务,实现负载均衡、端口映射、安全隔离等功能。
阅读原文:原文链接
该文章在 2025/7/1 10:58:40 编辑过