Connecting two docker containers

Viewed 35337

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.

3 Answers

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.

Related