Multiple docker containers with same container port connected to the same network

Abhijit Balaji picture Abhijit Balaji · Mar 16, 2019 · Viewed 10.2k times · Source

I am having an app that depends on multiple docker containers. I use docker compose so that all of them are in the same network for inter-container communication. But, two of my containers are listening to the same port 8080 inside their respective containers but, are mapped to different ports on the host: 8072,8073. For inter-container communication since we use the container's port will this cause problems?

Constraints:

  1. I need both the containers for my app to run. Thus I cannot isolate the other container with same internal port to a different network
  2. All containers should run on the same host.

Am new to docker and I am not sure how to solve this.

Thanks

Answer

DazWilkin picture DazWilkin · Mar 17, 2019

IIUC see the documentation here: https://docs.docker.com/compose/networking

You need not expose each of the service's ports on the host unless you wish to access them from the host, i.e. outside of the docker-compose created network.

Ports must be unique per host but each service in your docker-compose created network can use the same port with impunity and is referenced by :.

In the Docker example, there could be 2 Postgres services. Each would need a unique name: db1; db2 but both could use the same port - "5432" and be uniquely addressable from the service called web (and each other) as db1:8432 and db2:8432.

Each service corresponds effectively to a different host. So, as long as the ports are unique for each service|host, you're good. And, as long as any ports you expose on the host are unique, you're good too....

Extending the example, db1 could expose port 9432:8432 but then db2 would need to find a different host port to use, perhaps 9433:8432.

Within the docker-compose created network, you would access db1 as db1:8432 and db2 as db2:8432.

From the host (outside the docker-compose create network), you would access db1 as localhost:9432 and db2 as localhost:9433.

NB It's likely a good practice to only expose service ports to the host when those service's must be accessible from outside (e.g. web probably must be exposed but dbX probably need not be exposed). You may wish to be more liberal in exposing service ports while debugging.