Connect a running container to a network
In this step, you will learn how to connect a running Docker container to an existing network. This is useful when you have a container that is already running and you need it to communicate with other containers or services on a specific network.
First, let's create a new network that we will use for this demonstration. We will create a bridge network named my-network
.
docker network create my-network
You should see output similar to this, indicating the network was created successfully:
<network_id>
Now, let's run a simple container that is not initially connected to my-network
. We will run an alpine
container in detached mode (-d
) and name it my-container
.
docker run -d --name my-container alpine sleep infinity
The output will be the container ID:
<container_id>
To verify that the container is running and not connected to my-network
, you can inspect the container's network settings.
docker inspect my-container --format '{{json .NetworkSettings.Networks}}'
The output will show the default bridge network, but not my-network
:
{
"bridge": {
"IPAMData": null,
"IPAddress": "<ip_address>",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "<mac_address>",
"DriverOpts": null
}
}
Now, let's connect the running my-container
to the my-network
using the docker network connect
command.
docker network connect my-network my-container
There will be no output if the command is successful.
To verify that the container is now connected to my-network
, inspect the container's network settings again.
docker inspect my-container --format '{{json .NetworkSettings.Networks}}'
This time, the output should show both the default bridge network and my-network
:
{
"bridge": {
"IPAMData": null,
"IPAddress": "<ip_address>",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "<mac_address>",
"DriverOpts": null
},
"my-network": {
"IPAMData": null,
"IPAddress": "<ip_address>",
"IPPrefixLen": 24,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "<mac_address>",
"DriverOpts": null
}
}
Finally, let's clean up the container and the network we created.
docker stop my-container
docker rm my-container
docker network rm my-network