背景需求
使用docker構建應用系統,當應用系統增多的情況下,需要記住很多的IP/域名以及端口,尤其是端口號難記。需要通過不帶端口號的域名來訪問不同地址的不同端口所提供的服務。
例如:
a.zombie.com => 192.168.1.2:81
b.zombie.com => 192.168.1.2:82
c.zombie.com => 192.168.1.3:81
參考
環境
測試環境:
[root@localhost ~]# uname -r
3.10.0-229.el7.x86_64
[root@localhost ~]# cat /etc/redhat-release
CentOS Linux release 7.1.1503
[root@localhost ~]#
環境依賴:
1. 內網域名服務器:用於配置服務器的域名(或者公網的化可以使用自己購買的域名)
2. 2個web服務(後面的步驟中均已次爲例說明):
- ip_1:port_1
- ip_1:port_2
3. 1個nginx服務器
步驟
Web服務器準備
這個不再贅述,可以任意的Apache、Nginx、IIS等類型的web服務器。
ip_1:port_1
ip_2:port_2
Nginx安裝
說明:測試的時候未使用docker,直接使用的centos7虛擬機
- 安裝:
yum install nginx
- 啓動:
service nginx start
- 測試:看到類似下面的輸出就說明安裝成功了
nginx -v
nginx version: nginx/1.6.3
- 測試:訪問
http://localhost
可以看到首頁。
Nginx配置
配置文件位置
Centos:/etc/nginx/nginx.conf
日誌文件位置
日誌文件的位置在配置文件中配置,默認是/var/log/nginx/
DNS服務器配置域名
- 假設nginx服務器的ip地址爲:
192.168.1.10
- 配置2個域名均指向
192.168.1.10
,如下的域名、IP對應關係
域名 => IP
ip_1_port_1.zombie.com => 192.168.1.10
ip_2_port_2.zombie.com => 192.168.1.10
配置域名轉發
- 備份默認配置:mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
- 增加域名轉發配置:在http{}中增加如下內容
server {
listen 80;
server_name [domain_name];
location / {
proxy_pass [URL]
}
}
將[domain_name]換成上面配置的域名,[URL]換成對應的真是服務器地址。在本示例中,在http{}中增加如下內容
server {
listen 80;
server_name ip_1_port_1.zombie.com;
location / {
proxy_pass http://ip_1:port_1
}
}
server {
listen 80;
server_name ip_2_port_2.zombie.com;
location / {
proxy_pass http://ip_2:port_2
}
}
- 配置時保留原有的默認80端口配置(如下),這樣可以保留默認本機80端口的訪問,而不進行域名轉發。
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
測試驗證
- 設置本機的DNS服務器爲內網DNS服務器地址
- 打開瀏覽器
- 訪問
http://ip_1_port_1.zombie.com
,可以看到頁面的內容實際與http://ip_1:port_1
的相同 - 訪問
http://ip_2_port_2.zombie.com
,可以看到頁面的內容實際與http://ip_2:port_2
的相同
至此,nginx的域名轉發功能實驗完成了。
過程問題
- 在訪問的時候遇到如下問題
connect() to 127.0.0.1:8001 failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "localhost:8080"
解決辦法:參考http://stackoverflow.com/questions/23948527/13-permission-denied-while-connecting-to-upstreamnginx
- 訪問做了域名轉發的所有站點(一定要把所有的都訪問過)
- 執行
cat /var/log/audit/audit.log | grep nginx | grep denied
- 執行
cat /var/log/audit/audit.log | grep nginx | grep denied
- 執行
semodule -i mynginx.pp