Post

[Nest.js 학습일기] 도커 & Postgresql연결

[Nest.js 학습일기] 도커 & Postgresql연결

Docker

‘제 컴퓨터에선 잘 돌아가는데요?’와 같은 상황을 막기 위한 프로그램이다. 쉽게말해서 다양한 환경에서 동일한 환경을 구축하고 프로그램을 실행할 수 있는 환경을 제공하는 것. 이게 Docker의 목적이다.

Docker Compose

Docker에서 만드는 컨테이너가 많아질 때, 이를 관리하기 위한 도구이다.

docker-compose.yaml을 생성하고 docker-compose up 이란 명령어로 실행 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
services:
  postgres:
    image: postgres:15
    restart: always
    volumes:
      - ./postgres-data:/var/postgresql/data
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: postgres

postgres를 연결하는 docker-compose.yaml 예시

TypeOrm

table을 생성할 때, sql문이 아닌 typeScript를 사용해서 설치할 수 있도로 하는 도구라고 생각하면 된다. @nestjs/typeorm, typeorm을 설치하고 사용 가능한데, 사용법은 다음과 같다.

  1. 다음과 같이 파일을 생성한다. Next.js 프로젝트 구조
  2. 해당 파일을 다음처럼 작성한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 여기에 post 관련 모델 생성, sql문 대체

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity()
export class PostsModel {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  author: string;

  @Column()
  title: string;

  @Column()
  content: string;

  @Column()
  likeCount: number;

  @Column()
  commentCount: number;
}

데코레이터로 어떤 클레스를 생성할지 어떤게 칼럼인지 작성해야하고, id의 경우 (pk) @PrimaryGeneratedColumn()으로 고유값 기능을 하도록 해야 한다. (고유값이 보장되어야 정상 작동한다.)

이후 app.module.ts의 entity를 수정한다. typeorm을 등록하고 1번과 2번에서 수행한 모델 생성과정이 내용이 반영되도록 추가해야한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// app.module.ts 일부
@Module({
  imports: [
    PostsModule,
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'postgres',
      database: 'postgres',
      entities: [
        PostsModel,
      ],
      // 개발환경에선 싱크 맞추는게 편리. 그 외는 false
      synchronize: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

이후 이를 sql & database 관련 plugin으로 열어보면 정상 생성됨을 알 수 있다.

This post is licensed under CC BY 4.0 by the author.