【问题标题】:Communication between microservices with docker-compose and traefik使用 docker-compose 和 traefik 实现微服务之间的通信
【发布时间】:2019-07-12 19:41:21
【问题描述】:

我有一个基于微服务的节点应用程序。我正在使用 docker、docker-compose 和 traefik 进行服务发现。

此时我有 2 个微服务:

  • 服务器应用:在 node-app.localhost:8000 运行
  • 在 search-microservice.localhost:8002 运行的搜索微服务

我无法从一个微服务向另一个微服务发出请求的问题。 这是我的 docker compose 配置:

# 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

node-app 和 search-microservice 都暴露了 3000 端口。

为什么我不能从节点应用程序调用http://search-microservice.localhost:8002?但是从浏览器调用它是可行的。

【问题讨论】:

    标签: node.js docker docker-compose microservices traefik


    【解决方案1】:

    因为 node-app 是一个容器,并且要访问其他容器,它必须使用服务名称和内部端口

    在你的情况下是search-microservice:3000

    要访问主机 PC 和暴露的端口,您必须为所有服务和外部端口使用 host.docker.internal 名称。

    【讨论】:

    • 感谢您的回复,但由于在我的 docker-compose 配置中我有该服务的映射 8002:3000,我应该期望该服务可以通过 8002 访问吗?
    • 不完全是。暴露意味着可在外部访问。所以8002 将是您 host PC 上的端口,但在 docker bridge 网络中暴露没有任何效果。容器使用原始端口进行通信
    【解决方案2】:

    如果您想使用主机名从不同容器中访问其他服务,您可以在 docker-compose.yml 文件中使用“extra_hosts”参数。此外,您必须为每个所有服务使用网络参数下的“ipv4_address”参数。

    例如;

    services:
       node-app-1:
       container_name: node-app
       networks:
         apps:
           ipv4_address: 10.1.3.1
       extra_hosts:
         "search-microservice.localhost:10.1.3.2"
    
       node-app-2:
       container_name: search-microservice
       networks:
         apps:
           ipv4_address: 10.1.3.2
       extra_hosts:
         "node-app.localhost:10.1.3.1"
    

    Extra hosts in docker-compose

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 2021-11-27
      • 2022-07-16
      • 2018-07-17
      • 2019-05-19
      • 1970-01-01
      • 2016-06-10
      • 2020-09-04
      • 2020-03-12
      相关资源
      最近更新 更多