How to Connect a Docker Container to a Network
Use the
docker network connect command to attach an existing container to a Docker network. You can also specify the network when starting a container with docker run --network <network-name>.Syntax
The main commands to connect a container to a network are:
docker network connect <network-name> <container-name>: Connects a running container to an existing network.docker run --network <network-name> <image>: Starts a new container connected to the specified network.
Here, <network-name> is the name of the Docker network, <container-name> is the container's name or ID, and <image> is the Docker image to run.
bash
docker network connect <network-name> <container-name> docker run --network <network-name> <image>
Example
This example shows how to create a network, start a container on the default network, then connect it to the new network.
bash
docker network create my-network docker run -d --name my-container nginx docker network connect my-network my-container docker network inspect my-network
Output
[
{
"Name": "my-network",
"Id": "<network-id>",
"Created": "<timestamp>",
"Scope": "local",
"Driver": "bridge",
"Containers": {
"<container-id>": {
"Name": "my-container",
"EndpointID": "<endpoint-id>",
"MacAddress": "<mac-address>",
"IPv4Address": "172.18.0.2/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {}
}
]
Common Pitfalls
- Trying to connect a container to a network that does not exist will cause an error.
- Connecting a container to multiple networks can cause IP conflicts if not managed properly.
- Using
docker runwithout specifying--networkconnects the container to the default bridge network.
Always verify the network exists with docker network ls before connecting.
bash
docker network connect unknown-network my-container
# Error: network unknown-network not found
docker run -d --name my-container nginx
# Container connected to default bridge network
docker network connect my-network my-container
# Container now connected to both networksOutput
Error response from daemon: network unknown-network not found
Quick Reference
| Command | Description |
|---|---|
| docker network create | Create a new Docker network |
| docker network ls | List all Docker networks |
| docker run --network | Start container on specified network |
| docker network connect | Connect running container to network |
| docker network disconnect | Disconnect container from network |
Key Takeaways
Use 'docker network connect' to attach a running container to an existing network.
Specify '--network' option with 'docker run' to start a container on a specific network.
Always ensure the network exists before connecting containers to it.
Containers can be connected to multiple networks but watch for IP conflicts.
Use 'docker network ls' and 'docker network inspect' to manage and verify networks.