Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add containers to same network in Docker

Tags:

docker

I'm running containers with the docker run command and would like to add them to the same network such that each container is able to connect to each other using the container name.

I tried the following command: docker run --network=bridge (default docker network), but the containers couldn't connect to each other with their names.

How can I make it work?

like image 209
Tuomas Toivonen Avatar asked Jun 06 '18 13:06

Tuomas Toivonen


People also ask

Can two containers run on same port?

So there is no conflict if multiple containers are using the same port ( :80 in this case). You can access one container from another using its container-name or service-name or ip-address, whereas ip-address is not a good idea because this might change every time you (re)start the container.

Can we create multiple containers from the same image in Docker?

A Docker image executes code in a Docker container. You add a writable layer of core functionalities on a Docker image to create a running container. Think of a Docker container as a running image instance. You can create many containers from the same image, each with its own unique data and state.


2 Answers

First, define your user-defined bridge network:

docker network create your-network-name

Then, connect your containers to the network that you just created:

docker network connect your-network-name container-name

Or connect with the run command:

docker run --network=your-network-name your-image

Now, containers in the same network your-network-name can talk to each others via container name.

like image 192
Truong Dang Avatar answered Oct 06 '22 01:10

Truong Dang


You can attach a network to an existing container using this docker command:

docker network connect network-name container-name

Then, you can inspect using the network interface that you create that container was successfully connected or not.

docker inspect network-name
like image 25
Damith Udayanga Avatar answered Oct 06 '22 00:10

Damith Udayanga