使用NGINX代理的Docker负载平衡

Raj*_*Raj 5 nginx docker

我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我手动指定每台服务器,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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何配置nginx,使其可以检测到添加的新容器并将其包含在轮询中?

Raj*_*Raj 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
Run Code Online (Sandbox Code Playgroud)

工作 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)