How to Link Containers in Docker: Simple Guide
To link containers in Docker, create a user-defined network with
docker network create and run containers attached to this network using --network. Containers on the same network can communicate by container name without extra linking flags.Syntax
Linking containers is done by creating a network and attaching containers to it. The main commands are:
docker network create <network-name>: Creates a new network.docker run --network <network-name> --name <container-name> <image>: Runs a container attached to the network.
Containers on the same network can reach each other by their --name.
bash
docker network create my-network
docker run -d --name container1 --network my-network nginx
docker run -d --name container2 --network my-network alpine sleep 1000Example
This example creates a network, runs two containers on it, and shows how one container can ping the other by name.
bash
docker network create my-network
docker run -d --name webserver --network my-network nginx
docker run -it --rm --network my-network alpine sh -c "ping -c 3 webserver"Output
PING webserver (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.123 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.110 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.105 ms
--- webserver ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
Common Pitfalls
Common mistakes when linking containers include:
- Using the old
--linkflag, which is deprecated and less flexible. - Not creating or attaching containers to the same user-defined network, so they cannot resolve each other's names.
- Expecting containers on the default
bridgenetwork to communicate by name without extra setup.
Always use user-defined networks for container communication.
bash
docker run -d --name old-nginx nginx docker run -it --rm alpine ping old-nginx # This will fail because containers are on default bridge network and name resolution is not automatic. # Correct way: docker network create my-net docker run -d --name new-nginx --network my-net nginx docker run -it --rm --network my-net alpine ping new-nginx
Quick Reference
Summary tips for linking containers:
- Create a user-defined network with
docker network create. - Run containers with
--network <network-name>to connect them. - Use container names to communicate between containers.
- Avoid the deprecated
--linkflag.
Key Takeaways
Use user-defined Docker networks to link containers for easy name-based communication.
Attach containers to the same network using the --network flag when running them.
Avoid the deprecated --link option; it is less flexible and not recommended.
Containers on the default bridge network cannot resolve each other by name automatically.
Ping or connect to containers by their --name within the same network.