Create a basic bridge network
In this step, we will learn how to create a basic bridge network in Docker. A bridge network is the default network type for containers. Containers connected to the same bridge network can communicate with each other, while they are isolated from containers on other bridge networks and the host machine's network.
First, let's list the existing Docker networks to see the default ones.
docker network ls
You should see some default networks like bridge
, host
, and none
. The bridge
network is the one we will be working with.
Now, let's create a new bridge network. We will name it my-bridge-network
.
docker network create my-bridge-network
This command creates a new bridge network with default settings. Docker automatically assigns a subnet and gateway to this network.
To verify that the network was created successfully, list the Docker networks again.
docker network ls
You should now see my-bridge-network
in the list.
Next, let's inspect the newly created network to see its details, including the subnet and gateway assigned by Docker.
docker network inspect my-bridge-network
The output of this command will provide detailed information about the network, such as its ID, driver (which should be bridge
), and the subnet and gateway under the IPAM
section.
Now, let's run a container and connect it to our new network. We will use the alpine
image for this example. If you don't have the alpine
image locally, Docker will pull it automatically.
docker run -d --name container1 --network my-bridge-network alpine sleep infinity
This command runs a container named container1
in detached mode (-d
), connects it to my-bridge-network
(--network my-bridge-network
), and keeps it running by executing the sleep infinity
command.
To verify that the container is running and connected to the correct network, you can inspect the container.
docker inspect container1
In the output, look for the Networks
section. You should see my-bridge-network
listed, along with the IP address assigned to the container within that network.
Finally, let's run another container and connect it to the same network to demonstrate communication between them.
docker run -d --name container2 --network my-bridge-network alpine sleep infinity
Now, both container1
and container2
are connected to my-bridge-network
. They should be able to communicate with each other using their container names or IP addresses within the network.
To test communication, we can execute a command inside container1
to ping container2
. First, we need to install the iputils
package in the alpine containers to use the ping
command.
docker exec container1 apk add --no-cache iputils
docker exec container2 apk add --no-cache iputils
Now, ping container2
from container1
.
docker exec container1 ping -c 3 container2
You should see successful ping responses, indicating that the two containers on the same bridge network can communicate.