Creating a Network in Docker and Connecting a Container to That Network
Networks are created so that the devices which are inside that network can connect to each other and transfer of files can take place. In docker also we can create a network and can create a container and connect to the respective network and two containers that are connected to the same network can communicate with each other. These containers can also communicate with the host in which the docker is deployed. The communication will take place by using the IP address of each other. A container can connect to one or more networks in that docker host.
Step 1
In the first step we run a command to see the list of networks in your docker host.
sudo docker network ls
A bridge is the default network in docker.
Step 2
If you want to see the information regarding the particular network you can use the inspect command.
sudo docker network inspect docker_name
Notice that there is no container currently connected to the bridge driver as the brackets are empty.
Step 3
First we connect the container to the default bridge which is a driver provide default DNS service to the containers attached to it by running the command.
sudo docker run -it ubuntu:latest /bin/bash
To exit from the Ubuntu container which we just created use Ctrl + p then Ctrl + q. Now again run the docker inspect command to see the attached containers to the bridge.
Step 4
Now in this step we are going to create our own network and then in the next step connect the container to that network.
sudo docker network create --driver driver_name network_name
Description of the commands:
-
driver_name: name of the driver in this case we will use bridge driver.
-
network_name: name of the network you want to give to your network.
Now run the docker network ls command to see your created network.
Step 5
In this step, we will connect a container to our network which we have created in the previous step.
sudo docker run -it --network=new_nw ubuntu:latest /bin/bash
Step 6
Now inspect the network we created. The container we attach to the respected network is mentioned there.
This is the complete process to create the network and connect the container to it.