Node.js 微服务与docker compose和traefik之间的通信

Node.js 微服务与docker compose和traefik之间的通信,node.js,docker,docker-compose,microservices,traefik,Node.js,Docker,Docker Compose,Microservices,Traefik,我有一个基于微服务的节点应用程序。我正在使用docker、docker compose和traefik进行服务发现 目前我有2个微服务: 服务器应用程序:在节点应用程序上运行。本地主机:8000 运行在search microservice.localhost:8002上的search microservice 问题是我无法从一个微服务向另一个微服务发出请求。 以下是我的docker compose配置: # all variables used in this file are defin

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

目前我有2个微服务:

  • 服务器应用程序:在节点应用程序上运行。本地主机:8000
  • 运行在search microservice.localhost:8002上的search microservice
问题是我无法从一个微服务向另一个微服务发出请求。 以下是我的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
节点应用程序和搜索微服务都公开了端口3000


为什么我不能从节点应用程序呼叫?不过,从浏览器调用它也可以。

因为节点应用程序是一个容器,要访问其他容器,它必须使用服务名称和内部端口

在您的情况下,它是
搜索微服务:3000


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

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

比如,

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配置中,我有该服务的映射8002:3000,我希望该服务可以通过8002访问,对吗?不完全是这样。暴露意味着让外界可以接近。因此,
8002
将是主机PC上的端口,但docker网桥内部的网络暴露没有效果。容器使用原始端口进行通信