Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting two docker containers [duplicate]

I have two existing docker container web and db. I want to link these two container, so that they will communicate with each other. If i go with --link command means it will link web to a new image and not to the db.

like image 334
Ragul Avatar asked Aug 03 '17 10:08

Ragul


2 Answers

Using --link was the only way of connecting containers before the advent of docker networks. These provide a "cleaner" solution to the problem of inter-container communication and at the same time solves 2 of the major limits of links:

  1. restart of linked container breaks the link
  2. links are not supported between containers running on different hosts

Using docker network you would use the --net option to start the containers on the specified network:

docker network create example
docker run -d --net example --name container1 <image>
docker run -d --net example --name container2 <image>

At this point the 2 container are mutually reachable via the address <container-name>.example: that is container1.example and container2.example.

like image 61
nivox Avatar answered Oct 18 '22 01:10

nivox


Just to benefit people that stumble upon this question. The --link feature is now considered legacy and is a prime candidate to be deprecated by docker. The easiest way is to use

depends_on:

In order to do this, its recommended to first create a network like so:

docker network create <network_name>

Then use docker-compose to spawn services that bind with each other. Look at the example below where I've bound my spring-boot app to rabbit-mq. You can clone my repo from here.

version: "3.1"
services:
  rabbitmq-container:
    image: rabbitmq:3.5.3-management
    hostname: rabbitmq-container
    ports:
      - 5673:5673
      - 5672:5672
      - 15672:15672
    networks:
      - resolute

  resolute-container:
    build: .
    ports:
      - 8080:8080
    environment:
      - spring_rabbitmq_host=rabbitmq-container
      - spring_rabbitmq_port=5672
      - spring_rabbitmq_username=guest
      - spring_rabbitmq_password=guest
      - resolute_rabbitmq_publishQueueName=resolute-run-request
      - resolute_rabbitmq_exchange=resolute
    depends_on:
      - rabbitmq-container
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - resolute

networks:
  resolute:
    external:
      name: resolute

See how I've created a network called resolute and bound the apps to the same network. I've also given my rabbitmq-container a hostname. This is because docker now prepends the container name and that makes it difficult to bind services by name.

like image 33
Phani Bushan Avatar answered Oct 18 '22 01:10

Phani Bushan