Docker Containers Share Port Guide

In Docker, two containers are not allowed to share the same port since each port can only be bound to one container on the same host. If two containers need to use the same port, one can be mapped to the port of the other container, or Docker’s network modes can be used for communication between containers.

Here are two ways to implement it:

  1. Port mapping allows one container’s port to be mapped to another container’s port. For example, if container A needs to use port 8080 and container B also needs to use port 8080, you can map container A’s port to a port on the host (such as 8081), and then container B can use the host port 8081.
docker run -d -p 8081:8080 containerA
docker run -d -p 8080:8080 containerB
  1. Using Docker networks: you can create a custom network that allows two containers to be in the same network, so they can communicate with each other using the container name or IP address. For example, creating a network and adding container A and container B to that network.
docker network create mynetwork
docker run -d --name containerA --network mynetwork containerA
docker run -d --name containerB --network mynetwork containerB

This way, container A and container B can communicate with each other using container names without the need to share the same port.

bannerAds