Configuring Service Networking and Port Mapping
In this lesson, you will learn how to bridge the gap between isolated containers and the outside world by mastering service networking and port mapping.
By default, Docker containers are like secure rooms; they can talk to each other if they are on the same virtual network, but they remain unreachable from your host machine or the public internet. To make a service usable, you must explicitly define how traffic flows into and between your containers.
Understanding Port Mapping
Port mapping is the process of linking a specific port on your host machine to a port inside a container. Imagine you have a web server running inside a container on port 80. Without a map, that port is trapped. By declaring a port mapping in your docker-compose.yml, you effectively "open a window" to that container:
services:
web:
image: nginx:latest
ports:
- "8080:80"
In this example, traffic arriving at your host on port 8080 is automatically routed to port 80 inside the web container. This allows you to host multiple services on different host ports while keeping their internal configurations identical.
Service Networking
When you define multiple services—like a web frontend and a database backend—in a single docker-compose.yml, Docker automatically creates a dedicated bridge network. This allows services to communicate using their service names as hostnames, rather than relying on unreliable, ever-changing IP addresses.
For example, your web service can connect to your db service simply by using the hostname db. Because they are on the same network, the web service can reach the db service's internal port, even if the database port isn't exposed to the host machine. This approach keeps your infrastructure secure by ensuring only the necessary services are "mapped" to the outside world, while internal communication remains private and efficient.
By combining internal networking for service-to-service communication and host-to-container port mapping for public access, you create a robust architecture that is both secure and highly accessible.
Key Takeaway: Use port mapping to expose specific services to the host, and leverage internal service naming to ensure secure, reliable communication between containers within your network.