'How to Load balance containers using nginx

I aim to have 2 backend containers and an nginx container that will act as a loadbalancer.

This is my compose file:

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:

This is my nginx.conf:

events { worker_connections 1024; }

http {
    # List of application servers
    upstream api_servers {
        server cdn_nginx;
    }

    # Configuration for the server
    server {

        # Running port
        listen 80;

        # Proxying the connections
        location / {
        #return 200 'hello';
            proxy_pass         http://api_servers/;
        }
    }
}

When I run this I get:

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

When I enter the nginx and run :

ping cdn_nginx

It works (I get the currect IP adress, what do I do wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source