我正在尝试使用nginx和docker的本机DNS来加载平衡API服务器。
我希望nginx能够对所有可用服务器进行循环API调用。但即使我指定docker的DNS服务器作为解析器nginx也只能将请求转发给一个服务器。
docker-compose.yml的相关部分
proxy:
restart: always
build: ./src/nginx/.
ports:
- "8080:8080"
links:
- api:servers.api
nginx.conf
worker_processes 2;
events { worker_connections 1024; }
http {
sendfile on;
server {
listen 8080;
location / {
resolver_timeout 30s;
resolver 127.0.0.11 ipv6=off valid=10s;
set $backend http://servers.api:80;
proxy_pass $backend;
proxy_redirect off;
}
}
}
NGINX循环负载均衡器如果我手动指定每个服务器,我不想这样做,因为它无法自动扩展。
worker_processes 2;
events { worker_connections 1024; }
http{
sendfile on;
upstream api_servers{
server project_api_1:80;
server project_api_2:80;
server project_api_3:80;
}
server{
listen 8080;
location / {
proxy_pass http://api_servers;
proxy_redirect off;
}
}
}
如何以这样的方式配置nginx:它可以检测添加的新容器并将它们包含在循环中?
答案 0 :(得分:2)
我应该使用SERVICE名称作为nginx中的服务器名称而不是ALIAS名称。
在nginx容器上运行nslookup显示:
/ # nslookup api
nslookup: can't resolve '(null)': Name does not resolve
Name: api
Address 1: 172.20.0.7 project_api_1.project_default
Address 2: 172.20.0.5 project_api_3.project_default
Address 3: 172.20.0.6 project_api_2.project_default
/ # nslookup servers.api
nslookup: can't resolve '(null)': Name does not resolve
Name: servers.api
Address 1: 172.20.0.7 project_api_1.project_default
使用nginx.conf
worker_processes 2;
events { worker_connections 1024; }
http {
sendfile on;
server {
listen 8080;
location / {
resolver_timeout 30s;
resolver 127.0.0.11 ipv6=off valid=10s;
set $backend http://api:80;
proxy_pass $backend;
proxy_redirect off;
}
}
}
答案 1 :(得分:2)
在这种情况下,Docker的DNS负责执行循环操作。请勿在撰写it's not necessary中使用links
选项。看,我使用这个例子:
搬运工-compose.yml:
version: '3'
services:
api:
image: my-api-image
client:
image: ubuntu:latest
所以我使用docker-compose up -d api
启动我的应用程序,然后对其进行缩放:docker-compose scale api=10
。现在,在客户端(docker-compose run client bash
)内:
root@ce3857690292:/# dig api
...
;; QUESTION SECTION:
;api. IN A
;; ANSWER SECTION:
api. 600 IN A 172.19.0.6
api. 600 IN A 172.19.0.9
api. 600 IN A 172.19.0.7
api. 600 IN A 172.19.0.8
api. 600 IN A 172.19.0.11
api. 600 IN A 172.19.0.2
api. 600 IN A 172.19.0.10
api. 600 IN A 172.19.0.3
api. 600 IN A 172.19.0.5
api. 600 IN A 172.19.0.4
使用curl,您可以看到循环:
root@1719c10f864a:/# curl -vI api
* Rebuilt URL to: api/
* Trying 172.19.0.6...
* Connected to api (172.19.0.6) port 80 (#0)
...
root@1719c10f864a:/# curl -vI api
* Rebuilt URL to: api/
* Trying 172.19.0.7...
* Connected to api (172.19.0.7) port 80 (#0)
...
root@1719c10f864a:/# curl -vI api
* Rebuilt URL to: api/
* Trying 172.19.0.8...
* Connected to api (172.19.0.8) port 80 (#0)
在您的情况下,您需要使用您的nginx替换我的docker-compose中的客户端服务,并将您的api用作上游(不links
)