Cheug's Blog

当前位置:网站首页 / Linux / 正文

Nginx 四层透明代理(TCP Stream)

2026-05-15 / Linux / 3 次围观 / 0 次吐槽 /

1. 安装 Nginx

apt update && apt install nginx -y
apt install libnginx-mod-stream -y

2.Nginx 配置

四层代理使用的是 Nginx 的 stream 模块,这个模块必须与 http 模块平级,不能放在 http { ... } 内部,也不能放在默认的 conf.d 目录(因为该目录通常被 http 块 include)。

vi /etc/nginx/nginx.conf
# ==========================================
# 四层 TCP 透明代理配置 (必须与 http 块平级)
# ==========================================
stream {
    # 基础超时设置
    proxy_connect_timeout 5s;
    proxy_timeout 60s; 
    #  应用 1
    server {
        listen 9091;
        proxy_pass 192.168.10.45:9091;
    }
    #  应用 2
    server {
        listen 9092;
        proxy_pass 192.168.10.45:9092;
    }
    #  应用 3
    server {
        listen 9093;
        proxy_pass 192.168.10.45:9093;
    }
    #  应用 4
    server {
        listen 9094;
        proxy_pass 192.168.10.45:9094;
    }
    #  应用 5
    server {
        listen 9095;
        proxy_pass 192.168.10.45:9095;
    }
}


3. 测试并重启服务

nginx -t                 # 检查语法,确保输出 syntax is ok
systemctl restart nginx  # 重启 Nginx 使四层代理生效
systemctl enable nginx   # 设置为开机自启


主机内核高并发调优

由于主机承担了所有流量的中转,建议在 /etc/sysctl.conf 底部追加以下配置,以提升网络吞吐量和并发能力:

# 开启 BBR 拥塞控制
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

# 提升系统最大文件句柄数和网络连接队列
fs.file-max = 1000000
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535

# 优化 TIME_WAIT 状态快速回收
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_fin_timeout = 15

保存后执行 sysctl -p 使其立即生效。

Powered By Cheug's Blog

Copyright Cheug Rights Reserved.