Lesson 15: Exposing Ports and Inter-Container Communication
We need to distinguish between two port concepts: the container's internal port, and the host's exposed port.
1. EXPOSE (Dockerfile Instruction)
The EXPOSE instruction documents which port the application inside the container is listening on. It is purely informational and does not actually publish the port.
dockerfile
The application listens on port 80
EXPOSE 80
2. Publishing Ports (P Port Flag)
To make a container's port accessible from the host machine (and the outside world), you must use the -p (publish) flag during docker run.
Syntax: -p <Host Port>:<Container Port>
bash
Maps port 80 of the container to port 8000 on the host
docker run -d -p 8000:80 --name web_app nginx
Tip: If you only use a single -P (capital P), Docker will publish all exposed ports to random, high-numbered ports on the host. This is often useful for temporary testing.
3. Inter-Container Communication (Internal Networking)
When containers are on the same custom bridge network (Lesson 14), they can communicate without publishing ports to the host.
Example:
- A Frontend app (listening on 3000 inside its container).
- A Backend API (listening on 5000 inside its container).
If both are on my_custom_network:
- The Frontend needs to access the Backend API.
- The Frontend uses the URL:
http://backend_container_name:5000/api. - The Frontend does not need the host port mapping (e.g.,
-p 5000:5000) unless you also need to debug the API directly from your host machine.
Key Rule: Only expose ports (using -p) for services that need to be accessed directly by users or external systems (like a web server or a load balancer). Internal services like databases should remain unexposed.