Search code examples
node.jsdockerdocker-composemicroservicestraefik

Communication between microservices with docker-compose and traefik


I have a microservice based node app. I am using docker, docker-compose and traefik for service discovery.

I have 2 microservices at this moment:

  • the server app: running at node-app.localhost:8000
  • the search microservice running at search-microservice.localhost:8002

The issue I can't make a request from one microservice to another. Here are my docker compose config:

# all variables used in this file are defined in the .env file
version: "2.2"
services:
  node-app-0:
    container_name: node-app
    restart: always
    build: ./backend/server
    links:
      - ${DB_HOST}
    depends_on:
      - ${DB_HOST}
    ports:
      - "8000:3000"
    labels:
      - "traefik.port=80"
      - "traefik.frontend.rule=Host:node-app.localhost"
  reverse-proxy:
    image: traefik # The official Traefik docker image
    command: --api --docker # Enables the web UI and tells Traefik to listen to docker
    ports:
      - "80:80"     # The HTTP port
      - "8080:8080" # The Web UI (enabled by --api)
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
  search-microservice:
    container_name: ${CONTAINER_NAME_SEARCH}
    restart: always
    build: ./backend/search-service
    links:
      - ${DB_HOST}
    depends_on:
      - ${DB_HOST}
    ports:
      - "8002:3000"
    labels:
      - "traefik.port=80"
      - "traefik.frontend.rule=Host:search-microservice.localhost"
volumes:
  node-ts-app-volume:
    external: true

Both the node-app and the search-microservice expose the port 3000.

Why can't I call http://search-microservice.localhost:8002 from the node app ? calling it from the browser works though.


Solution

  • Because node-app is a container and to access other containers it has to use service name and internal port.

    In your case it is search-microservice:3000.

    To access host PC and exposed ports, you have to use host.docker.internal name for all services and external port.