Module 4 Lesson 3: Container Networking Basics
How containers talk to each other. Explore Docker's built-in networking modes and learn how to create private networks for secure inter-container communication.
Module 4 Lesson 3: Container Networking Basics
By default, Docker containers are isolated. If you have a web-app container and a database container, they cannot see each other unless you specifically build a "Bridge" between them.
1. The Three Default Networks
When you install Docker, it creates three networks for you:
- Bridge: The default. Good for single containers running on one host.
- Host: The container shares the host machine's IP address. There is no isolation. (Fast but insecure).
- None: No networking. The container is a "locked room."
2. User-Defined Bridge Networks
The "Professional Way" is to create your own networks. Why? Because on the default Bridge, containers can only talk to each other via IP Addresses (which change every time you restart!).
On a User-Defined Network, Docker provides automatic DNS Service Discovery.
The Workflow:
- Create a network:
docker network create my-app-net - Attach containers to it:
docker run --name db --network my-app-net -d postgres docker run --name web --network my-app-net -d my-web-app - Communication:
Now, your
webapp can connect to the database using the hostnamedbinstead of an IP address! Docker's internal DNS handles the translation.
Visualizing the Process
graph TD
Start[Input] --> Process[Processing]
Process --> Decision{Check}
Decision -->|Success| End[Complete]
Decision -->|Retry| Process
3. Exposing vs. Publishing Ports
- Expose (Internal): Declares that the container listens on a port. Only other containers on the same network can see it.
- Publish (External): Mapping a port to your host (using
-p). This makes it available to the outside world (your browser).
Security Tip: Never publish your Database port (-p 5432:5432) to the outside world. Keep it "Exposed" only to the web-app on a private network.
4. Useful Network Commands
docker network ls: List all networks.docker network inspect <name>: See which containers are attached and their IP addresses.docker network connect <net> <container>: Add a running container to an existing network.
Exercise: The Network Connectivity Test
- Create a network called
island-net. - Run two containers using the
alpineimage on that network:container-aandcontainer-b.- Hint:
docker run -d --name container-a --network island-net alpine sleep 1000
- Hint:
- "Jump inside"
container-ausingexec. - Try to
ping container-b. Does it work? - Try to
ping google.com. Does it work? (If yes, why? Containers have outbound internet access by default).
Summary
Networking is what turns isolated "Boxes" into a functioning "System." By using User-Defined Bridge networks, you gain the power of Service Discovery, allowing your apps to talk to each other by name rather than unpredictable IP addresses.
Next Lesson: Data that survives: Volumes and persistent storage.