When running multiple Docker containers, one common question is:
“Can containers connect to each other using their container names?”
The answer is Yes!
But — only if they are on the same custom Docker network.
1. Why the Default Network Doesn’t Work
By default, Docker creates a bridge network (also known as docker0).
However, this default bridge network does not support automatic DNS name resolution,
so containers can only communicate using IP addresses.
That’s fine for quick tests, but IPs change often, making it hard to maintain.
2. Create a Custom Network
To enable name-based communication, create a custom network:
docker network create mynet
Containers attached to this network will be able to resolve each other’s names automatically.
3. Attach Containers to the Same Network
Run containers on that network:
docker run -d --name web --network mynet nginx
docker run -d --name app --network mynet alpine sleep infinity
Both web and app are now on mynet.
4. Connect via Container Names
Enter one container (e.g. app) and test the connection:
docker exec -it app sh
ping web
nc -zv web 80
Docker’s internal DNS will resolve web to the web container’s IP automatically.
No need to remember IPs — just use the container name!
5. Using Network Aliases
If you want a shorter or alternate name, set a network alias:
docker run -d --name db --network mynet --network-alias mysql mysql:8
Now other containers can reach it using the name mysql.
✅ Summary
| Condition | Description |
|---|---|
| Same custom network | Enables DNS name resolution |
| Default bridge | No name resolution, IP only |
| Use alias | Optional alternate names |
In short:
When containers share the same custom Docker network, they can communicate over TCP/UDP using container names or aliases — no IP required.