How to create a bidirectional link between containers?

前端 未结 5 1245
梦如初夏
梦如初夏 2020-11-30 01:00

I have to link two containers so they can see each other. Of course the following...

docker run -i -t --name container1 --link container2:container2 ubuntu:t         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 01:53

    Here's how I've solved this for myself:

    First, I go through all my containers (which need to know from each other) and create dnsmasq entries like so:

    for f in container1 container2 container3; do
      IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' $f 2>/dev/null`
      if [ -n "$IP" ]; then
        echo $f "$IP"
        echo "host-record=$f,$IP" > /etc/dnsmasq.d/0host_$f
      else
        rm -f /etc/dnsmasq.d/0host_$f
      fi
    done
    

    Then I start a dns container which has dnsmasq-base installed and starts the dnsmasq service:

    docker run -d -P -h dns --name dns -v /etc/dnsmasq.d:/etc/dnsmasq.d:ro dns
    

    then I get the IP address of this container:

    DNS_IP=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' dns`
    

    And start the containers like so:

    docker run -d -P -h container1 --name container1 --dns $DNS_IP container1
    docker run -d -P -h container2 --name container2 --dns $DNS_IP container2
    docker run -d -P -h container3 --name container3 --dns $DNS_IP container3
    

    This is a simplified version of my setup but it shows the gist. I've also added a mechanism that forces dnsmasq to rescan when files in /etc/dnsmasq.d change via inotify-tools. That way all containers get the new ip address whenever one container is restarted.

提交回复
热议问题