gpt4 book ai didi

使用 NGINX 代理进行 Docker 负载平衡

转载 作者:行者123 更新时间:2023-12-02 04:40:33 24 4
gpt4 key购买 nike

我正在尝试使用 nginx 和 docker 的 native 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,使其能够检测添加的新容器并将其包含在循环中?

最佳答案

在这种情况下,Docker 的 DNS 负责执行循环。不要在撰写中使用 links 选项,it's not necessary 。看,我正在使用这个例子:

docker-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 作为上游(没有链接)

关于使用 NGINX 代理进行 Docker 负载平衡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49836080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com