繁体   English   中英

使用 docker-compose 和 traefik 实现微服务之间的通信

[英]Communication between microservices with docker-compose and traefik

我有一个基于微服务的节点应用程序。 我正在使用 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-app 是一个容器并且要访问其他容器,它必须使用 service name 和internal port

在您的情况下,它是search-microservice:3000

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

如果要使用主机名从不同容器中访问其他服务,可以使用 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"

docker-compose 中的额外主机

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM