Stop using Docker "--link" command ๐Ÿ’ข

Stop using Docker "--link" command ๐Ÿ’ข

ยท

2 min read

When we have multiple containers running for our application stack then we might need them to be able to talk to each other and share data, one way to do it is by using "--link <image name> : <host name>" but this method is a legacy feature and deprecated to use. So what should we use instead of --link?

Enter Docker compose ->

A better way to achieve this is by using link inside the docker-compose YAML file. When we create the docker-compose YAML file we can pass the arguments required to link different containers inside the YAML file.

Let's implement it with an example:

For our example, we will take the sample voting app provided by docker itself.

GitHub link -> https://github.com/dockersamples/example-voting-app

First, we do it the traditional way :

docker run -d --name=redis redis
docker run -d --name=db postgres:9.4
docker run -d --name=vote -p 5000:80 --link redis:redis voting-app
docker run -d --name=result -p 5001:80 --link db:db result-app
docker run -d --name=worker - -link db:db --link redis:redis worker

The app architecture will look as

When we run the above commands one by one we need to link the containers using "--link" but with docker-compose, we can do it as :

services:
  vote:
    build: ./vote
    depends_on:
      redis:
        condition: service_healthy
    ports:
      - "5000:80"
    networks:
      - front-tier
      - back-tier

  result:
    build: ./result
    ports:
      - "5001:80"
      - "5858:5858"
    networks:
      - front-tier
      - back-tier

  worker:
    build:
      context: ./worker
    depends_on:
      redis:
        condition: service_healthy 
      db:
        condition: service_healthy 
    networks:
      - back-tier

  redis:
    image: redis:alpine
    networks:
      - back-tier

  db:
    image: postgres:15-alpine
    environment:
      POSTGRES_USER: "postgres"
      POSTGRES_PASSWORD: "postgres"
    networks:
      - back-tier

networks:
  front-tier:
  back-tier:

The app architecture will look as

In the above YAML file, we have provided link inside of it, we have also used network tiers which can be used to deal with client traffic and backend processes individually.

We don't need to run the docker commands one by one all we need to do is run

docker compose up [OPTIONS] [SERVICE...]

and our application will be up and running.

Thanks for reading my blog ๐Ÿ™Œ๐Ÿผ

ย