Search code examples
dockerdocker-network

Docker network bridge


I'm trying to run multiple containers with the same ports on docker.

For this, I have created a network in brigde mode and specified a subnet.

docker network create -d --subnet 192.168.99.0/24 mynetwork

Then connected the docker containers to it with a static IP.

docker run -i -t -d -p 2377:2377 -p 7946:7946 -p 4789:4789-name container image
docker network connect --ip 192.168.99.98 mynetwork container

I did this with three containers (using different IP's), after starting the second one I got:

Error response from daemon: driver failed programming external connectivity on endpoint container(...): Bind for 0.0.0.0:7946 failed: port is already allocated

As far as I'm concerned, I should not be getting this error, due to bridge mode.


Solution

  • The docker run -p option allocates a port on the host system; those are shared across all containers, independently of what Docker-private network they’re using. These also will conflict with non-Docker processes running on the host.

    If your goal is just to be able to communicate between containers on the same network, you don’t need a -p option at all. They can use each others’ --name and the port the service inside the container is listening on to connect.

    If you’re trying to run multiple Docker container stacks at the same time, you need to decide which specific instance port 2377 on your host will route to, and change the other container’ -p option.

    Specifically setting the Docker-internal private IP addresses (or worrying about them at all) is almost never necessary. I’d delete those --subnet and --ip options. To communicate between containers, put them on the same network as described above; from outside you need a (unique) -p option.