Connect from one Docker container to another

后端 未结 7 1647
故里飘歌
故里飘歌 2020-12-04 18:11

I want to run rabbitmq-server in one docker container and connect to it from another container using celery (http://celeryproject.org/)

I have rabbitmq running using

相关标签:
7条回答
  • 2020-12-04 19:16

    [edit 2016]

    Direct links are deprecated now. The new way to do link containers is docker network connect. It works quite similar to virtual networks and has a wider feature set than the old way of linking.

    First you create your named containers:

    docker run --name rabbitmq -d -p :5672 markellul/rabbitmq /usr/sbin/rabbitmq-server
    docker run --name celery -it markellul/celery /bin/bash
    

    Then you create a network (last parameter is your network name):

    docker network create -d bridge --subnet 172.25.0.0/16 mynetwork
    

    Connect the containers to your newly created network:

    docker network connect mynetwork rabbitmq
    docker network connect mynetwork celery
    

    Now, both containers are in the same network and can communicate with each other.

    A very detailed user guide can be found at Work with networks: Connect containers.

    [old answer]

    There is a new feature in Docker 0.6.5 called linking, which is meant to help the communication between docker containers.

    First, create your rabbitmq container as usual. Note that i also used the new "name" feature which makes life a litte bit easier:

    docker run --name rabbitmq -d -p :5672 markellul/rabbitmq /usr/sbin/rabbitmq-server
    

    You can use the link parameter to map a container (we use the name here, the id would be ok too):

    docker run --link rabbitmq:amq -i -t markellul/celery /bin/bash
    

    Now you have access to the IP and Port of the rabbitmq container because docker automatically added some environmental variables:

    $AMQ_PORT_5672_TCP_ADDR
    $AMQ_PORT_5672_TCP_PORT
    

    In addition Docker adds a host entry for the source container to the /etc/hosts file. In this example amq will be a defined host in the container.
    From Docker documentation:

    Unlike host entries in the /etc/hosts file, IP addresses stored in the environment variables are not automatically updated if the source container is restarted. We recommend using the host entries in /etc/hosts to resolve the IP address of linked containers.

    0 讨论(0)
提交回复
热议问题