傳統上 TCP 代理常用 HAProxy,但自 Nginx 1.9 版本引入 stream 模塊後,Nginx 也能勝任四層(傳輸層)代理。優勢在於:
地址:https://nginx.org/en/download.html
# 1. 創建 yum 源文件
vim /etc/yum.repos.d/nginx.repo
# 寫入以下內容
[nginx]
name=nginx repo
baseurl=https://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
# 2. 安裝
yum clean all
yum install nginx
# 3. 驗證安裝
whereis nginx
/usr/sbin/nginx -v
# 輸出: nginx version: nginx/1.10.1
# 4. 查看默認配置路徑
/usr/sbin/nginx -h
# -c filename : set configuration file (default: /etc/nginx/nginx.conf)
建議將配置、日誌、腳本與安裝程序分離,便於遷移與備份。
# 創建目錄結構
mkdir -p /opt/service/nginx/conf
mkdir -p /opt/logs/nginx
cd /opt/service/nginx
ln -s /usr/sbin/nginx
ln -s /opt/logs/nginx log
最終結構:
/opt/service/nginx/
├── conf
├── log -> /opt/logs/nginx
└── nginx -> /usr/sbin/nginx
user nginx;
worker_processes 16; # 通常設置為 CPU 核心數
worker_rlimit_nofile 100000; # 打開文件描述符限制
error_log /opt/service/nginx/log/error.log error;
pid /opt/service/nginx/nginx.pid;
events {
use epoll; # Linux 內核高效事件模型
worker_connections 10240; # 單進程最大連接數
}
# 核心:包含 conf 目錄下所有 .conf 文件,實現模塊化配置
include /opt/service/nginx/conf/*.conf;
使用 stream 塊(與 http 塊同級)定義四層代理。
stream {
# 定義上游服務器組
upstream weixin_proxy {
# 一致性哈希,保證同一客戶端固定訪問同一後端(有狀態協議需求時)
hash $remote_addr consistent;
server wx.qq.com:443 weight=1 max_fails=3 fail_timeout=60s;
}
server {
listen 443; # 監聽本地 443 端口
proxy_connect_timeout 10s; # 連接後端超時
proxy_pass weixin_proxy; # 轉發到上游組
proxy_buffer_size 64k; # 代理緩衝區大小
}
}
提供 start|stop|restart|reload|check 命令,生產環境建議配置為 Systemd 服務,但 Shell 腳本便於快速部署與調試。
#!/bin/sh
nginx="/usr/sbin/nginx"
prog="nginx"
conf_file="/etc/nginx/nginx.conf" # 注意:腳本中指定的配置文件路徑需與實際一致
start() {
if [ `pgrep $prog | wc -l` -eq 0 ]; then
if [ -x $nginx ] && [ -f $conf_file ]; then
$nginx -c $conf_file
# ... 成功失敗判斷邏輯 ...
fi
else
echo "$prog is already started"
fi
}
stop() {
# ... killall -9 $prog 邏輯 ...
}
reload() {
# ... kill -HUP master_pid 熱加載邏輯 ...
}
check() {
$nginx -t -c $conf_file # 配置檢查
}
case $1 in
start) start ;;
stop) stop ;;
restart) stop; sleep 2; start ;;
reload) reload ;;
check) check ;;
*) echo "Usage: $0 {start|stop|restart|reload|check}" ;;
esac
賦權並啟動:
chmod a+rwx nginx.sh
./nginx.sh restart
問題:upstream 中使用域名(如 wx.qq.com),Nginx 啟動時解析 IP 並緩存。若域名 IP 變更(如雲服務商切換 IP),Nginx 不會自動感知,導致代理失效。
解決方案:在 stream 或 http 上下文中配置 resolver 指令,並配合變量強制動態解析(需 Nginx Plus 或 OpenResty 完美支持,社區版有限制)。
# 在 nginx.conf 主上下文添加
resolver 100.100.2.136 valid=1s; # 使用內網 DNS,TTL 1 秒
# include /etc/nginx/nginx_vhost/*.conf;
注意:社區版 Nginx 在 stream 模塊中對動態解析支持有限,生產環境強依賴域名解析更新的場景,建議使用 OpenResty 或 HAProxy,或配合腳本定期 reload。
Nginx 的 stream 模塊為四層代理提供了輕量、高性能的原生支持。通過模塊化配置、標準化部署目錄與健壯的啟動腳本,可快速構建穩定的 TCP 代理集群。但需注意域名解析緩存機制,根據業務關鍵性選擇合適的解決方案。