Container Networking & Embedded DNS
Custom Bridges, Service Discovery, and Why localhost Fails Between Containers
What You Will Master:
- Understand why `localhost` inside container A cannot reach container B
- Create user-defined bridge networks with `docker network create`
- Use Docker automatic DNS resolution to connect microservices
1The `localhost` Trap
A frequent beginner mistake is trying to make container frontend call http://localhost:5000 to reach backend.
Why this fails: Each container has its own isolated network namespace and loopback interface (127.0.0.1). Inside frontend, localhost refers strictly to frontend itself, not other containers or the host machine!
2User-Defined Bridge & Docker DNS
When you create a custom bridge network: ``bash docker network create app-net ` Docker activates an embedded DNS server (127.0.0.11). Containers attached to app-net can communicate simply using each other's container names (e.g. http://api:5000`).
Connect Two Containers on Custom Network
Create a network named `app-net` and run a backend container attached to it.
Step 1: Create network named app-net
Run `docker network create app-net`
Step 2: Run api container on app-net
Run `docker run -d --name api --network app-net node:22-alpine`
Chapter Knowledge Quiz
Pass the 3-question assessment to earn +50 XP and complete this chapter.