skip to Main Content

I need to start several docker containers on a Linux machine, each will ran same networked program which listens on same port number. I can’t use host network or port mapping since all containers must listen on same local port.

All these containers run on same bridge network, I can ping them from host but I can’t connect, the connection is always refused.

2

Answers


  1. What you are asking for is possible, and really not too difficult, but probably not advisable.
    If you have some really specific requirement, or some app that can’t be load balanced for some reason, the following solution should still work:

    In docker, when you start a container, it’s registered to a ip. From the same host, this ip is reachable for most network types, like host or bridge.
    By targeting this ip directly you can use any ports you like to connect to the container.
    Getting this ip can either be done from within the container, via something like ip addr show, or perhaps more easily from outside via docker commands.
    From docker ps you can get the ids of the containers you are interested in. For each of those you can then call docker inspect $id. That will give you some json data about the container, including the ip of the container. Note, in some situations, one container can be in multiple networks, so you would be able to access the same container in multiple ports.

    The following expression would give you the first possible ip by which a container is reachable:

    function container_ip {
      id_or_name="$1"
      IP_FORM='{{range $a, $b := .NetworkSettings.Networks}}{{$b.IPAddress}} {{end}}'
      docker inspect "$id_or_name" --format "$IP_FORM" | head -1
    }
    

    You can then call this for each container id you have to get the correct ip, and connect to your containers directly.
    If you are sure that every one of the containers is in only one network, you could also be a bit quicker, by just directly executing:

    IP_FORM='{{range $a, $b := .NetworkSettings.Networks}}{{$b.IPAddress}} {{end}}'
    docker inspect --format "$IP_FORM" $id1 $id2 ... $idn
    

    and you will directly get a line separated list of ips.

    Login or Signup to reply.
  2. nginz proxy manager would solve this and its really easy to setup.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search