Docker Port Binding Cheatsheet
Port binding (or port mapping) is a key mechanism for enabling network communication between a container and the host machine. It maps a port from the host to a port inside the container.
How It Works
A container is isolated from the host by default. To make a service running inside a container accessible from the outside world (or from the host itself), you need to explicitly map a host port to the container's port. The docker run -p flag is used for this.
docker run -p 8080:80 [IMAGE_NAME]In this example:
-p: The flag for publishing a port.8080: The **host port**. This is the port you will use to access the service from your web browser or another machine.80: The **container port**. This is the port on which your application inside the container is listening.
Port Binding in a Table
| Command | Description |
|---|---|
docker run -p 8080:80 [IMAGE] | Binds a specific host port (8080) to a specific container port (80). |
docker run -p 80:80 [IMAGE] | A common scenario where the host and container ports are the same. |
docker run -p 127.0.0.1:8080:80 [IMAGE] | Binds the container port to a specific host IP address. This is useful if you have multiple network interfaces and want to restrict access. |
docker run -p 8080 [IMAGE] | Binds a random host port to the container's exposed port. Docker will automatically assign a free port on the host. |
docker port [CONTAINER_ID] | Shows the current port mappings for a running container. |