一:用nginx做反向代理
為了解決這兩個問題,自然第一反應想到的就是使用反向代理,我的理想構思下應該是下圖這樣的。
既用戶所有的請求都經過nginx,讓nginx來判斷當前url需要跳轉到哪一個后端代理上,比較好的策略應該是讓nginx來判斷當前的host是什么來決定跳轉到后端的哪一個webserver上,比如a.mip.com 就跳轉到apollo,j.mip.com 就跳轉到jenkins. 以此類推,這樣就可以完美解決了,是吧? 在nginx中你完全可以使用rewrite模塊下if指令來進行判斷。
這里要提一下,nginx比較原始化,如果需使用第三方module,你還需要重新編譯nginx,用起來很麻煩,所以這里干脆使用OpenResty,它擴展了nginx,并且集成了很多成熟的lua模塊,自行下載最新的1.15.8,安裝方式和nginx一模一樣。
默認是安裝到/usr/local/目錄下,當你看到有一個openresty目錄表示你安裝成功。
[root@localhost local]# lsbin 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 -vnginx 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。
1. 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]# ls50x.html apollo.html index.html jenkins.html
2. jenkins的模擬
server { listen 8002; server_name somename alias another.alias; location / { root html; index jenkins.html; } }
jenkins.html的文件所在路徑如上所示哈。不再贅述。
3. proxy的模擬
可以看到,只需要使用rewrite模塊下的if條件語句,通過$host系統變量判斷當前的url中的host的值跳轉到相應的網站。
4. host映射
好了,接下來只需要將a.mip.com 和 j.mip.com 映射到nginx的ip地址192.168.23.129即可。因為這些域名方便記憶而不是真實存在的。
192.168.23.129 a.mip.com192.168.23.129 j.mip.com
5. 啟動nginx
[root@localhost sbin]# ./nginx [root@localhost sbin]# [root@localhost sbin]# [root@localhost sbin]# netstat -tlnpActive 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 端口都已經開啟了,接下來大家可以到瀏覽器去驗證一下了。
可以看到這個問題已經很完美的解決了,好了,這就是本篇和大家聊到的實際場景中遇到的一個問題,希望本篇對你有幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。