Based on my understanding port mapping is 1 to 1, what I don't understand is why the data structure used for port mapping in container data is like this,
"NetworkSettings": {
[...]
"Ports": {
"8888/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "8888"
}
]
}
The "8888/tcp"
key maps to a list instead of single object. Thus in a Java client the data structure for Ports is like this Map<String, List<PortBinding>>
, but the List
here can only contain 1 element right? Or did I terribly miss something fundamental?
So there is no conflict if multiple containers are using the same port ( :80 in this case). You can access one container from another using its container-name or service-name or ip-address, whereas ip-address is not a good idea because this might change every time you (re)start the container.
Surprisingly or not, neither Docker nor Podman support exposing multiple containers on the same host's port right out of the box. Example: docker-compose failing scenario with "Service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash."
To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world.
0.1 . It means containers can't use the same port. It's very easy to achieve this with the help of docker run or docker-compose , by using 8001:80 for the first container and 8002:80 for the second container.
This is perfectly legal:
docker run -tid -p 8080:80 -p 8090:80 nginx
"Ports": {
"443/tcp": null,
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "8090"
},
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
So no, it's not 1 to 1.
johnharris85 's answer is correct. Here, I want to points out that you can map multiple host ports to the same container port and the opposite is impossible(except they have different IP address). Just think about how can the postman deliver things to two houses, with the same house number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With