Apollo Gateway 无法在 docker-compose 内工作

ra9*_*a9r 5 docker microservices docker-compose graphql apollo-server

我正在尝试使用 Docker 和 docker-compose 设置一个简单的联合 Apollo 网关,但似乎无法让网关连接到模式服务。

这是docker-compose.yml文件

version: "3.9"
services:
  gateway:
    build: ./api-gateway
    ports:
      - 4000:8080
    depends_on:
      - robots
      - sitemaps
    environment:
      APOLLO_KEY: ${APOLLO_KEY}
    volumes:
      - ../secrets/credentials.json:/tmp/key/credentials.json
      - ./api-gateway/index.js:/usr/src/app/index.js
  
  robots:
    build: ./api-robots
    ports:
      - 4001:8080
    environment:
      GOOGLE_APPLICATION_CREDENTIALS: /tmp/key/credentials.json
    volumes:
      - ../secrets/credentials.json:/tmp/key/credentials.json
      - ./api-robots/src:/usr/src/app/src


  sitemaps:
    build: ./api-sitemaps
    ports:
      - 4002:8080
    environment:
      GOOGLE_APPLICATION_CREDENTIALS: /tmp/key/credentials.json
    volumes:
      - ../secrets/credentials.json:/tmp/key/credentials.json
      - ./api-sitemaps/src:/usr/src/app/src
Run Code Online (Sandbox Code Playgroud)

在网关代码中,我使用以下命令注册robots和服务:sitemaps

const { ApolloServer } = require("apollo-server");
const { ApolloGateway } = require("@apollo/gateway");

// Initialize an ApolloGateway instance and pass it an array of
// the implementing service names and URLs
const gateway = new ApolloGateway({
  serviceList: [
    { name: "robots", url: "http://robots:4001" },
    { name: "sitemaps", url: "http://sitemaps:4002" },
  ],
});

const server = new ApolloServer({
  gateway,
  subscriptions: false,
});

server
  .listen(8080)
  .then(({ url }) => {
    console.log(` Gateway Server ready at ${url}`);
  })
  .catch((err) => {
    console.error("Failed to start Gateway");
  });

Run Code Online (Sandbox Code Playgroud)

然而,当它运行时,我收到网关服务报告的以下错误:

gateway_1   | Error checking for changes to service definitions: Couldn't load service definitions for "robots" at http://robots:4001: request to http://robots:4001/ failed, reason: connect ECONNREFUSED 172.19.0.3:4001
gateway_1   | This data graph is missing a valid configuration. Couldn't load service definitions for "robots" at http://robots:4001: request to http://robots:4001/ failed, reason: connect ECONNREFUSED 172.19.0.3:4001
Run Code Online (Sandbox Code Playgroud)

我知道这些服务工作正常,因为我能够分别从主机和处连接到robots和服务;并且两者都可以正常工作。sitemapshttp://localhost:4001http://localhost:4002

我已经阅读了无数关于此的主题,我发现的最常见问题是其他人错误地尝试连接localhost而不是使用服务名称(例如robotssitemaps)作为​​域名。我不会犯这样的错误。

这是我尝试过的其他一些方法,但也不起作用......

  • 创建自定义networks定义并将其分配给每个服务
  • 连接到http://robots:8080http://sitemaps:8080
  • 连接到http://localhost:4001http://localhost:4002

我究竟做错了什么?

小智 0

您应该请求端口 8080 而不是 4001,仅此而已。应该是http://robots:8080并且http://sitemaps:8080