如何使用 nginx 进行容器负载均衡

我希望有2个后端容器和一个充当负载均衡器的 nginx 容器。

这是我的compose文件

version: '3.3'

services:
    api_backend:
        container_name: api_backend
        hostname: api_backend
        build: ./api_backend_server/
        restart: always
        networks:
          - routing_net

    cdn_backend:
        container_name: cdn_backend
        hostname: cdn_backend
        build: ./cdn_server/
        restart: always
        networks:
          - routing_net

    nginx:
        depends_on:
          - api_backend
          - cdn_backend
        build: ./externalNginx/
        ports:
          - 80:80
          - 443:443
        restart: always
        networks:
          - routing_net

networks:
  routing_net:

这是我的 nginx.conf

events { worker_connections 1024; }

http {
    # 应用服务器列表
    upstream api_servers {
        server cdn_nginx;
    }

    # 服务器配置
    server {

        # 运行端口
        listen 80;

        # 代理连接
        location / {
        #return 200 'hello';
            proxy_pass         http://api_servers/;
        }
    }
}

当我运行时,我得到以下结果:

nginx_1        | 2022/01/31 16:54:03 [emerg] 1#1: host not found in upstream "cdn_nginx" in /usr/local/openresty/nginx/conf/nginx.conf:6

当我进入 nginx 并运行:

ping cdn_nginx

它可以工作(我得到正确的 IP 地址),我做错了什么?

原文链接 https://stackoverflow.com/questions/70929868

点赞