Creating a Custom Network
To create a custom network in Docker, you can use the docker network create
command. This command allows you to specify the network driver, subnet, and other configuration options.
Create a Custom Bridge Network
Let's create a custom bridge network named my-network
:
docker network create my-network
You can verify the network creation using the docker network ls
command:
NETWORK ID NAME DRIVER SCOPE
a1b2c3d4e5f6 my-network bridge local
Connect Containers to the Custom Network
Now, let's start two containers and connect them to the my-network
custom network:
## Start container 1
docker run -d --name container1 --network my-network ubuntu:22.04 sleep infinity
## Start container 2
docker run -d --name container2 --network my-network ubuntu:22.04 sleep infinity
You can inspect the network and see the connected containers using the docker network inspect
command:
[
{
"Name": "my-network",
"Id": "a1b2c3d4e5f6",
"Created": "2023-04-18T12:34:56.789Z",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": {},
"Config": [
{
"Subnet": "172.18.0.0/16"
}
]
},
"Internal": false,
"Attachable": false,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"container1_id": {
"Name": "container1",
"EndpointID": "container1_endpoint_id",
"MacAddress": "02:42:ac:12:00:02",
"IPv4Address": "172.18.0.2/16",
"IPv6Address": ""
},
"container2_id": {
"Name": "container2",
"EndpointID": "container2_endpoint_id",
"MacAddress": "02:42:ac:12:00:03",
"IPv4Address": "172.18.0.3/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
Now that we have created a custom network and connected containers to it, we can test the communication between the containers in the next section.