如何讓多個不同類型的後端網站用一個nginx進行反向代理實際場景分析
前段時間公司根據要求需要将聚石塔上伺服器從杭州整體遷移到張家口,剛好趁這次機會将這些亂七八糟的伺服器做一次梳理和整合,斷斷續續一個月遷移完
成大概優化掉了1/3的機器,完成之後遇到了一些問題,比如曾今零零散散部署在生産上一些可視化UI:apollo,kibana,grafana,jenkins 等等要麼采用80端口,要
麼對公開放了其他端口,為了安全,現在不再開放非80之外的公網端口,由于機器少了,80端口不夠,這些可視化UI不再能直接通路到了。是以需另尋其他出路。
一:用nginx做反向代理
為了解決這兩個問題,自然第一反應想到的就是使用反向代理,我的理想構思下應該是下圖這樣的。
既使用者所有的請求都經過nginx,讓nginx來判斷目前url需要跳轉到哪一個後端代理上,比較好的政策應該是讓nginx來判斷目前的host是什麼來決定跳轉到後端
的哪一個webserver上,比如a.mip.com 就跳轉到apollo,j.mip.com 就跳轉到jenkins. 以此類推,這樣就可以完美解決了,是吧? 在nginx中你完全可以使用rewrite
子產品下if指令來進行判斷。
二:使用if指令
這裡要提一下,nginx比較原始化,如果需使用第三方module,你還需要重新編譯nginx,用起來很麻煩,是以這裡幹脆使用OpenResty,它擴充了nginx,并且
內建了很多成熟的lua子產品,自行下載下傳最新的1.15.8,安裝方式和nginx一模一樣。
預設是安裝到/usr/local/目錄下,當你看到有一個openresty目錄表示你安裝成功。
[root@localhost local]# ls
bin etc games include lib lib64 libexec openresty sbin share src
[root@localhost local]# pwd
/usr/local
接下來你可以使用 nginx -v 來看一下openresty版本号啥的。
[root@localhost sbin]# pwd
/usr/local/openresty/nginx/sbin
[root@localhost sbin]#
[root@localhost sbin]# ./nginx -v
nginx version: openresty/1.15.8.1
為了友善,我就直接使用nginx開啟三個server:
<1> 192.168.23.129:80 nginx上開啟的第一個網站,就是proxy了。
<2> 192.168.23.129:8001 nginx上開啟的第二個網站,模拟apollo。
<3> 192.168.23.129:8002 nginx上開啟的第三個網站,模拟jenkins。
- apollo的模拟:
server {
listen 8001;
server_name somename alias another.alias;
location / {
root html;
index apollo.html;
}
}
8001端口網站的預設頁是apollo.html,這個apollo.html所在路徑就是在nginx下的html目錄,如下所示。
[root@localhost html]# pwd
/usr/local/openresty/nginx/html
[root@localhost html]# ls
50x.html apollo.html index.html jenkins.html
- jenkins的模拟
server {
listen 8002;
server_name somename alias another.alias;
location / {
root html;
index jenkins.html;
}
}
jenkins.html的檔案所在路徑如上所示哈。不再贅述。
- proxy的模拟
server {
listen 80;
server_name localhost;
location / {
if ($host = "a.mip.com") {
proxy_pass http://localhost:8001;
}
if ($host = "j.mip.com") {
proxy_pass http://localhost:8002;
}
}
可以看到,隻需要使用rewrite子產品下的if條件語句,通過$host系統變量判斷目前的url中的host的值跳轉到相應的網站。
- host映射
好了,接下來隻需要将a.mip.com 和 j.mip.com 映射到nginx的ip位址192.168.23.129即可。因為這些域名友善記憶而不是真實存在的。
192.168.23.129 a.mip.com
192.168.23.129 j.mip.com
- 啟動nginx
[root@localhost sbin]# ./nginx
[root@localhost sbin]# netstat -tlnp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8001 0.0.0.0:* LISTEN 3802/nginx: master
tcp 0 0 0.0.0.0:8002 0.0.0.0:* LISTEN 3802/nginx: master
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 3802/nginx: master
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1172/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1724/master
tcp6 0 0 :::22 :::* LISTEN 1172/sshd
tcp6 0 0 ::1:25 :::* LISTEN 1724/master
通過上圖可以看到,80,8001,8002 端口都已經開啟了,接下來大家可以到浏覽器去驗證一下了。
可以看到這個問題已經很完美的解決了,好了,這就是本篇和大家聊到的實際場景中遇到的一個問題,希望本篇對你有幫助,以下是全部的nginx.conf。
View Code
原文位址
https://www.cnblogs.com/huangxincheng/p/11790007.html