使用docker容器學習 Nginx 反向代理
概述:
使用的鏡像是官網上的nginx, 創建了3個容器實例,
爲了方便, 分別啓動了以下三個端口,90端口的實例,對外服務,
9001 和 9002 端口的實例通過link被90實例反向代理。
當然,也可以都啓動在80端口上。
90
/ \
|9001|
|9002|
1. 啓動9001容器
cd 9001
docker run -d
--name n9001 \
-v $(pwd)/conf:/etc/nginx \
-v $(pwd)/html:/etc/nginx/html \
nginx:1.9
2. 啓動9002容器
cd 9002
docker run -it --rm --name n9002 \
-p 9002:9002 \
-v $(pwd)/conf:/etc/nginx \
-v $(pwd)/html:/etc/nginx/html \
nginx:1.9
3. 啓動代理服務器
docker run -it --rm --name n90 \
-p 90:90 \
--link
n9001:node1 \
--link
n9002:node2 \
-v $(pwd)/conf:/etc/nginx \
nginx:1.9
4. 測試
curl http://localhost:90
代理輸出
172.17.0.1 - - [04/Jun/2016:13:31:57 +0000] "GET / HTTP/1.1" 200 277"-" "curl/7.29.0"
172.17.0.1 - - [04/Jun/2016:13:32:07 +0000] "GET / HTTP/1.1" 200 277"-" "curl/7.29.0"
172.17.0.1 - - [04/Jun/2016:13:32:09 +0000] "GET / HTTP/1.1" 200 277"-" "curl/7.29.0"
172.17.0.1 - - [04/Jun/2016:13:32:10 +0000] "GET / HTTP/1.1" 200 274"-" "curl/7.29.0"
節點n9001輸出
[root@ip-172-30-0-110 ~]# docker logs n9001
172.17.0.4 - - [04/Jun/2016:13:31:57 +0000] "GET / HTTP/1.0" 200 277"-" "curl/7.29.0"
172.17.0.4 - - [04/Jun/2016:13:32:07 +0000] "GET / HTTP/1.0" 200 277"-" "curl/7.29.0"
172.17.0.4 - - [04/Jun/2016:13:32:09 +0000] "GET / HTTP/1.0" 200 277"-" "curl/7.29.0"
[root@ip-172-30-0-110 ~]#
節點n9002輸出
172.17.0.4 - - [04/Jun/2016:13:32:10 +0000] "GET / HTTP/1.0" 200 274"-" "curl/7.29.0"
5. 使用 命令
dockerinspect n90 檢查容器, 其中與link
相關的部分:
"Links": [
"/n9001:/n90/node1",
"/n9002:/n90/node2"
],
6. 文件樹結構
.
├── 90
│ └── conf
│
├── conf.d
│
│ └──default.conf
│
├──fastcgi_params
│
├── html
│
├── koi-utf
│
├── koi-win
│
├── mime.types
│
├── modules ->/usr/lib/nginx/modules
│
├── nginx.conf
│
├── nginx.conf.0
│
├── scgi_params
│
├── uwsgi_params
│
└── win-utf
├── 9001
│ ├── conf
│ │ ├── nginx.conf
│ └── html
│
├── 50x.html
│
└── index.html
└── 9002
├── conf
│ ├── nginx.conf
└── html
├── 50x.html
└── index.html
7.附配置:
節點服務器: /etc/nginx/nginx.conf
worker_processes
auto;
error_log
/var/log/nginx/error.logwarn;
pid
/var/run/nginx.pid;
events {
worker_connections
1024;
}
http {
include
/etc/nginx/mime.types;
default_type
application/octet-stream;
server {
listen 9002;
}
}
代理服務器: /etc/nginx/nginx.conf
worker_processes auto;
events {
worker_connections 1024;
}
http {
tcp_nodelay on;
upstream myCluster {
server node1:9001
weight=5;
server node2:9002;
#這樣表示5/6的機率訪問第一個server,1/6訪問第二個
}
server {
listen 90;
#
location ~ \.html$ {
location / {
proxy_pass
http://myCluster;
#這裏的名字和上面的cluster的名字相同
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP$remote_addr;
proxy_set_header X-Forwarded-For$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto$scheme;
}
}
}