docker-compose 和 traefik 微服务之间的通信

Communication between microservices with docker-compose and traefik

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

此时我有 2 个微服务:

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

# 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 是一个容器,要访问其他容器,它必须使用服务名称和内部端口

你的情况是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"

Extra hosts in docker-compose