Home > database >  Can not connect to another container when ports map to different ports
Can not connect to another container when ports map to different ports

Time:10-14

I have two services running in Docker containers. When the ports map to the same ports, i.e. 9120:9120 and 9121:9121, then everything works correctly.

However, the containers can not connect to each other when the ports map to different port numbers as shown in this Docker compose file:

  version: "3.9"
  networks:
    service_net:
      name: service_net

  services: 
    base_service:
      build: 
        context: .
        dockerfile: base_service/Dockerfile
      networks: 
        - service_net
      image: base_service
      container_name: base_service
      ports:
        - "19120:9120"
      restart: unless-stopped

    # The second_service uses base_service
    second_service:
      build: 
        context: .
        dockerfile: second_service/Dockerfile
        args:
          BASE_SERVICE_HOST: base_service
          BASE_SERVICE_PORT: 19120
      networks: 
        - service_net
      image: second_service
      container_name: second_service
      ports:
        - "19121:9121"
      restart: unless-stopped

What could be the reason?

CodePudding user response:

The containers them self and other containers in the same network, will see the internal ports.

In this example, all containers running in service_net have access to 9120 and 9121. To fix the problem, change BASE_SERVICE_PORT to 9120 in the Docker compose file.

I fell into this trap and only figured out what was wrong after a debug session. This fact could be described better in docs.docker.com/config/containers/container-networking/ in my opinion.

CodePudding user response:

The numbers in the ports line mean the following:

    ports: 
    - <port-as-known-on-localhost>:<port-as-known-inside-the-docker-compose-network>

If you do this:

    ports:
    - 444:555

Accessing the container from the host where the containers are running on should be done on port 444

Accessing the container from another container inside the compose-network should be done on port 555

  • Related