NestJs - Docker 的两个微服务之间的通信

时间:2021-06-21 07:23:56

标签: docker microservices nestjs docker-image

问题

我使用 Nestjs 实现了一个微服务应用程序,包括一个 auth 服务和一个 api 网关 超过 TCP 的 docker 服务名称如下:

  • api-gateway => app.module.ts
import { Inject, Module } from '@nestjs/common';
import { ClientProxy, ClientsModule, Transport } from '@nestjs/microservices';
import { AuthController } from './auth.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { GoogleStrategy } from './auth/strategies/google.strategy';

@Module({
  
  imports: [
    ClientsModule.register([
      {
        name:'SERVICE_AUTH',
        transport:Transport.TCP,
        options:{
          host: 'auth',
          port: 9090
        }
      },
    ])
    ,UserModule, AuthModule],
  controllers: [AuthController],
  providers: [AppService,GoogleStrategy],
  
})
export class AppModule {
  @Inject("SERVICE_AUTH") private readonly clientServiceA: ClientProxy
}
  • auth-microservice => ma​​in.ts
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { Logger } from "@nestjs/common";

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.TCP,
    options: {
      host: "api-gateway",
      port: 9090
    }
  });
  app.listen(() => Logger.log("Microservice Auth is listening"));
}
bootstrap();

我基于 docker 文件单独构建他们的图像,而不使用 docker-compose。但是当它们在同一网络上像下图一样运行时,api-gateway 无法访问 auth 服务:

输出错误

[Nest] 1   - 06/21/2021, 8:26:05 AM   [ClientTCP] Error: getaddrinfo EAI_AGAIN auth +32740ms
My error:  Error: getaddrinfo EAI_AGAIN auth
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {
  errno: -3001,
  code: 'EAI_AGAIN',
  syscall: 'getaddrinfo',
  hostname: 'auth'
}
  • 通过api-gateway调用auth微服务的方法时控制台错误图片:

enter image description here

任何一点都可以帮助我。

谢谢

0 个答案:

没有答案