Can multiple Docker containers run using the same

2019-02-05 23:38发布

问题:

Been looking into using Docker for a REST service project. One question I have is whether we could use Docker to run multiple versions of the service on the same host/port.

For example, I want to have an endpoint at {myserver}:8080/v1/ and another at {myserver}:8080/v2/.

If it's relevant at all, these would be Java:8 based Docker images constructed with a java jar on the Spring Boot REST framework.

Is this possible with Docker containers?

回答1:

You can run both containers using different host ports, and use a haproxy/nginx/varnish (native or inside another container) listening to the host port, and redirecting to the right container based on the URL.



回答2:

This is as much a question about the way tcp ports work as the way docker works. In the same way that two applications can't bind to the same tcp port, neither can two docker containers.

As @Sergei Rodionov points out SO_REUSEPORT can be used to allow multiple processes to share the same tcp port (and this can be specified when launching your java application). I don't think this will work across containers.



回答3:

Yes, this is possible as long as you are using different network addresses for each duplicate port you are listening on.

For example, your host has the following IPs assigned to it: 192.168.11.223 10.88.88.12

You could have two separate containers both listening on: 192.168.11.223:80 10.88.88.12:80

If you look at the syntax for docker run:

-p=[]      : Publish a container᾿s port or a range of ports to the host 
             format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
             Both hostPort and containerPort can be specified as a range of ports. 
             When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`)
             (use 'docker port' to see the actual mapping)


回答4:

yes, it is possible as long as containers are using different IP address. you can check the IP address of the containers by using below command.

docker inspect -f '{{ .NetworkSettings.IPAddress }}' <container ID>


标签: docker port