How to create a bidirectional link between containers?

前端 未结 5 1247
梦如初夏
梦如初夏 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:37

    There is no bi-directional link since you can not link to a non-running container.

    Unless you are disabling inter-container communication, all containers on the same host can see any other containers on the network. All you need is to provide them the ip address of the container you want to contact.

    The simplest way of knowing the ip address of a container is to run:

    docker inspect --format '{{ .NetworkSettings.IPAddress }}' container1
    

    You can look it up after starting both containers (just don't use --link).

    If you need to know the IP of container2 from inside container1 automatically, there are a few options:

    1. Mount the docker socket as a volume and use the remote API

      docker run -i -t --name container1 -v /var/run/docker.sock:docker.sock ubuntu:trusty /bin/bash echo -e "GET /containers/container2/json HTTP/1.0\r\n" | nc -U /docker.sock | sed 's/.IPAddress":"([0-9.]).*/\1/'

    2. Use an orchestration service… there are so many to choose from, but I personally like the DNS-based ones like Skydock or registrator and access containers by dns name.

    3. Use a docker management service (such as dockerize.it —disclaimer: I am working on it—) that will setup the DNS services for you.

提交回复
热议问题