개발일지

Nest.js MSA 도커파일 , 도커 컴포즈

index.ys 2023. 12. 23. 19:37

app.service.ts

  • 특정 엔드포인트로 접근발생시  COMMUNICATION, ANALYTICS로 TCP프로토콜 전송
  • user_created라는 이벤트 발생, 다른 앱 서비스에서 user_created라는 이벤트를 수신하고 상황에 맞는 동작처리
  • ex)회원가입시 사용자의 email을 저장하고 email로 가입메세지를 전송할 수 있음
import { Inject, Injectable } from '@nestjs/common';
import { CONTEXT, ClientProxy } from '@nestjs/microservices';
import { CreateUserRequest } from './create-user-request.dto';
import { CreateUserEvent } from './create-user.event';

@Injectable()
export class AppService {
  private readonly users: any[] = [];

  constructor(
    @Inject('COMMUNICATION') private readonly communicationClient: ClientProxy,
    @Inject('ANALYTICS') private readonly analyticsClient: ClientProxy,
  ) {}

  //3000번 포트 backend 디렉
  getHello(): string {
    return 'Hello World!';
  }

  async createUser(createUserRequest: CreateUserRequest) {
    //users배열에 createUSerReust추가
    //createUser
    this.users.push(createUserRequest);

    //communicationClint의 emit 메서드를 실행
    //user_created 이벤트 발생
    //CreateUserEvent 객체 생성, 사용자의 email전송
    this.communicationClient.emit(
      'user_created',
      new CreateUserEvent(createUserRequest.email),
    );

    this.analyticsClient.emit(
      'user_created',
      new CreateUserEvent(createUserRequest.email),
    );

    return '메세지가 발송 되었습니다.';
  }

  getAnalytics() {
    return this.analyticsClient.send({ cmd: 'get_analytics' }, {});
  }
}

도커파일

  • 3개의 서비스를 포트만 바꿔서 컨테이너로 각각 실행
  • 3000,3001,3002 포트 사용 => EXPOSE에서 3000, 3001 , 3002 각각 디렉토리에서 도커파일 옵션 변경
# Use a specific version of Node.js as a base image
FROM node:20

# Create app directory
WORKDIR /usr/src/app

# Copy package.json and package-lock.json separately to leverage Docker caching
COPY package.json ./
COPY yarn.lock ./

# Install app dependencies
RUN yarn install

# Bundle app source
COPY . .

# Creates a "dist" folder with the production build
RUN yarn build

# Expose the port that the app will run on
EXPOSE 3000

# Start the server using the production build
CMD ["yarn", "start:prod"]

도커 컴포즈 파일

version: '3'

services:
  sample-backend:
    build:
      context: ./sample-backend
      dockerfile: dockerfile
    ports:
      - "3000:3000"
    networks:
      - nest-network

  sample-communication:
    build:
      context: ./sample-communication
      dockerfile: dockerfile
    ports:
      - "3001:3001"
    networks:
      - nest-network

  sample-analytics:
    build:
      context: ./sample-analytics
      dockerfile: dockerfile
    ports:
      - "3002:3002"
    networks:
      - nest-network

networks:
  nest-network:
    driver: bridge

 

ㄷ심심해서 만든 깃허브 오토커밋 쉘 스크립트

  • 실행 명령어 : sh 파일명.sh
  • ex) sh gitcommit.sh
  • git add . git commit -m "메세지", git push origin master 순으로 명령어 실행하여 자동으로 origin레포에 push가능
#!/bin/sh
start_time=$(date +%s)
end_time=$(date +%s)
echo "깃커밋을 실행합니다.$start_time"
git add . 
git commit -m "코드팩토리 강의"
git push origin master
echo "깃커밋을 종료합니다.$end_time

실행결과