chaitanya
chaitanya

Reputation: 55

Docker multiple same port issue

I am currently working on two inter related ASP.NET Core WebAPI services (Service1 & Service2) in a solution. Both are having docker files and exposing port 80.

Service1 is an independent service and required to be called from Service2. I have given both docker-compose.yml and docker-compose.override.yml.

docker-compose.yml

version: '3.4'

    services:
      services1:
        image: ${DOCKER_REGISTRY-}services1
        network_mode: bridge
        build:
          context: .
          dockerfile: Services1/Dockerfile
        ports:
         - "501:80"

      services2:
        image: ${DOCKER_REGISTRY-}services2
        network_mode: bridge
        build:
          context: .
          Services2/Dockerfile
        ports:
         - "502:80"

docker-compose.override.yml

version: '3.4'

services:
  services1:
    build:
      context: .
      dockerfile: Services1/Dockerfile
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    ports:
      - "1001:80"

  services2:
    build:
      context: .
      dockerfile: Services2/Dockerfile
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - SERVICE1=http://localhost:1001
      ports:
      - "1002:80"    

When i call http://localhost:1001 from http://localhost:1002 with network_mode: bridge, I am getting the below exception.

{System.Net.Http.HttpRequestException: Cannot assign requested address ---> System.Net.Sockets.SocketException: Cannot assign requested address

when i change the network_mode to host ( network_mode:host ), i am getting the below exception.

System.IO.IOException: 'Failed to bind to address http://[::]:80: address already in use.'

So please let me know how to resolve the issue.

Upvotes: 2

Views: 9364

Answers (2)

Siyu
Siyu

Reputation: 12119

You should stick with the default bridge mode (by removing network_mode: bridge) and change

  - SERVICE1=http://localhost:1001

to

  - SERVICE1=http://services1:80 # services1 will be resolved by docker

Because service1 and service2 are on separate containers, so there is no opened port 1001 on the container of service2.

Upvotes: 6

Kyaw Kyaw Soe
Kyaw Kyaw Soe

Reputation: 3370

From internal you can use container name instead of host and port (actually it's more practical), you can find your container name by typing docker ps in your terminal.

e.g. if you call service 1 from service 2 use http://asp_project_service1

Upvotes: 0

Related Questions