In this lesson, you will learn how to assign custom network aliases to containers so your services can communicate using stable, human-readable hostnames rather than volatile container names.
The Problem with Container Names
By default, when you attach a container to a custom Docker bridge network, it is reachable via its container name through Docker’s embedded DNS. While convenient, this creates a tight coupling: if you rename your container or recreate it with a new name, any other service trying to connect to it will break. In a distributed architecture, you want your application code to point to a stable address, such as db or auth-service, regardless of what the underlying container is actually called.
Implementing Network Aliases
To decouple your service’s internal identity from its container name, you can assign one or more "aliases" within your network configuration. An alias is essentially a DNS record that resolves to the container's IP address only within that specific network.
If you are using docker run, you can define these aliases using the --network-alias flag:
docker network create my-app-net
docker run -d \
--name web-app-v1-production \
--network my-app-net \
--network-alias my-api \
my-image
In this example, other containers on my-app-net can now communicate with this container by sending requests to http://my-api:8080. Even if you destroy the web-app-v1-production container and launch a new one under a different name (e.g., web-app-v2), as long as you assign it the my-api alias, the connection remains uninterrupted.
Scaling via Aliases
This approach is particularly powerful for service discovery. When you scale a service, you can assign the same alias to multiple containers. Docker’s embedded DNS will then return a list of IP addresses for that alias, enabling simple client-side load balancing. By focusing on these aliases in your application configuration, you create a layer of abstraction that keeps your architecture flexible and resilient to underlying container changes.
Key Takeaway: Network aliases provide a stable DNS abstraction layer that allows services to communicate using consistent, logical hostnames, effectively decoupling your application logic from specific container naming conventions.