使用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;
}
}
}