Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Docker map multiple container ports to one host port?

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?

like image 879
Derek Avatar asked Jun 07 '16 22:06

Derek


People also ask

Can multiple containers expose same port?

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.

Can two Docker containers expose same port?

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."

How do I map a container port to a host port?

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.

Can two containers use the same port in a pod?

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.


2 Answers

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.

like image 125
johnharris85 Avatar answered Sep 22 '22 10:09

johnharris85


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.

like image 35
Shawn Avatar answered Sep 21 '22 10:09

Shawn