nginx 從 1.9.0 開始針對 nginx opensource 版本(也就是一般人常用到的版本)加上了 ngx_stream_core_module 功能以便於實現 nginx 於 TCP/UDP 的代理及負載平衡。目前像是使用 yum、apt install 等等的套件安裝依舊停留於 nginx 1.18,使用負載平衡功能時需要手動編譯安裝以便於安裝 ngx_stream_core_module 功能。
編譯 nginx 並且加上 ngx_stream_core_module 功能
先移除現有 nginx ,如果有相關配置的話請先記得保存備份
apt remove nginx
下載 nginx 1.19 版本,解壓縮後進入目錄中
wget https://nginx.org/download/nginx-1.19.0.tar.gz
tar zxf nginx-1.19.0.tar.gz
cd nginx-1.19.0
輸入配置選項,其中需要包含 --with-stream
及 --with-stream_ssl_module
,所有安裝參數可以在 這裡 找到,這邊只安裝最低限度資訊。
./configure --prefix=/var/www/html --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --modules-path=/etc/nginx/modules --with-stream --with-stream_ssl_module --without-http_rewrite_module
在執行上方指令如果遇到 ./configure: error: C compiler cc is not found
,請記得先安裝 C 編譯器 apt install gcc
後再次執行。
另外如果出現 ./configure: error: SSL modules require the OpenSSL library.
的話,請安裝 openssl 模組:apt-get install libssl-dev
當跳出以下畫面時,便可進行下一步咯!

接著輸入 make
開始編譯,如果沒有安裝 make 的人可以透過 apt install make
安裝。
安裝完成後,輸入 make install
來安裝。
以上步驟完成後,可以輸入 nginx -v
來確認當前版本,確定安裝完成。
[email protected]:~/nginx-1.19.0# nginx -v
nginx version: nginx/1.19.0
TCP Stream 配置
為了未來配置方便,我們要把 stream 文件獨立出來。為此我們必須先到 nginx.cong
先定義我們未來存放的路徑
前往 /etc/nginx/nginx.conf
開啟後,在最下面加上
stream {
include stream/*conf;
}
然後在 /etc/nginx 資料夾下面創立一個 stream 資料夾 mkdir stream
必且進入 cd stream
mkdir stream
cd stream
隨便創建一個 conf 檔案,這次我們目的是為了透過這台主機連線到其他主機的 SSH 端口,因此我們就創建一個 ssh22.conf
的檔案好了,配置內容如下:
upstream ssl {
server 103.172.92.32:22;
}
server {
listen 1234;
proxy_pass ssl;
}
其中 upstream 主 103.172.92.32 是目的主機 IP,22 為端口。server 部分監聽 1234 端口,並將流量 pass 到 upstream ssl 中,其中 upstream 可以輸入多個 server,同時扮演負載平衡的角色。
接著要重新啟動 nginx ,但在這之前我們要先創建 nginx.service 檔案才可以透過 systemctl 更方便的 restart nginx。
創建 /lib/systemd/system/nginx.service
檔案,並且輸入以下內容:
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
保存後輸入 systemctl restart nginx
,便可透過 你的主機IP:1234 連線到目標主機IP ( 103.172.92.32 ) 的 SSH 咯!