Search code examples
node.jsdockernestjs

NestJS Microservice Issue with Docker


I am trying to create NestJS micro-service and accessing it with a client gateway using docker container. When I ran it locally it works fine but when I deploy it on docker it gives me below error. I have two different docker files one for gateway and one for microserice.

[Nest] 1 - 03/06/2021, 10:11:19 PM [ExceptionsHandler] connect ECONNREFUSED 127.0.0.1:4000 +19833ms
Error: connect ECONNREFUSED 127.0.0.1:4000
at TCPConnectWrap.afterConnect [as oncomplet]

Dockerfile.gateway

FROM node:12.18-alpine
RUN mkdir -p /custom-root
WORKDIR /custom-root
COPY ./package.json .
COPY ./nest-cli.json .
COPY ./tsconfig.json .
COPY ./tsconfig.build.json .
COPY ./apps/gateway-client/. ./apps/gateway-client/.
RUN npm install -g @nestjs/cli
RUN npm install
RUN npm run build gateway-client
EXPOSE 3001
CMD [ "node", "./dist/apps/gateway-client/main.js" ]

Service docker file

FROM node:12.18-alpine
RUN mkdir -p /custom-root
WORKDIR /custom-root
COPY ./package.json .
COPY ./nest-cli.json .
COPY ./tsconfig.json .
COPY ./tsconfig.build.json .
COPY ./apps/service-customer/. ./apps/service-customer/.
RUN npm install -g @nestjs/cli
RUN npm install
RUN npm run build service-customer
EXPOSE 4000
CMD [ "node", "./dist/apps/service-customer/main.js" ]

Here is the Service file TCP connection

async function bootstrap() {
  const { SERVICE_CUSTOMER_PORT, SERVICE_CUSTOMER_HOST } = process.env;
  const port = SERVICE_CUSTOMER_PORT || 4000;
  const host = SERVICE_CUSTOMER_HOST || '0.0.0.0';
  const app = await NestFactory.createMicroservice(CustomerModule, {
    transport: Transport.TCP,
    options: {
      host,
      port
    },
  });
  app.listen(() => logger.log(`Customer Microservice is listening at ${port} host -> ${host}`));
}
bootstrap();

Here is the Code for gateway

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const { GATEWAY_PORT } = process.env;
  const port = GATEWAY_PORT || 3001
  await app.listen(port);
}
bootstrap();

Please help


Solution

  • Noticed, you are using NestJS to create your micro-services and api-gateway both. In order to containerise them separately, you need to create separate hybrid application to communicate through http. Please have a look at Expose normal http endpoint in NestJS Microservices.

    Here is an article that can help in splitting the apps.
    How to split Nest.js microservices into separate projects?.

    Post that, you can containerise all those different hybrid apps(micro-services over http) and configure them at your api gateway or any channel where the communication can happen.