개발 여정/Web

[Node.js] PM2 (Process Manager)

calm-lee 2023. 4. 6. 17:51

 

PM2

홈페이지 정의

PM2 is a daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via NPM.

 

 

Node.js 어플리케이션을 쉽게 관리할 수 있게 해주는 Process Manager로, 다음과 같은 기능을 제공한다.

  • Cluster mode 제공
  • 메모리 관리
  • 에러 관리

 

 

Cluster mode

  • Node.js는 기본적으로 싱글 스레드임
  • 싱글 쓰레드는 구동 중인 CPU 개수와 상관 없이 1개만 사용할 수 있기 때문에 서버 성능을 제대로 끌어내지 못함
  • 반면 멀티쓰레드는 최대 서버 CPU만큼 프로세스를 끌어내 최대 성능을 끌어낼 수 있음
  • PM2의 cluster 모드는 이를 멀티 쓰레드로 구동시켜줄 수 있음

 

PM2에서 Cluster mode 사용하기 

// ecosystem.config.js
module.exports = {
  apps : [{
    script    : "app.js", 
    instances : "max", // 실행시킬 프로세스의 개수(max로 입력할 경우 최대 개수로 설정한다.)
    exec_mode : "cluster" // cluster 모드로 어플리케이션을 구동시킨다.
  }]
}

 

 

PM2 시작하기

명령어: pm2 start ecosystem.config.js

 

 

PM2 모니터링

PM2를 모니터링하면 다음 항목들을 실시간으로 확인 가능하다.

  • 각 프로세스의 메모리, CPU 사용률, 현재 상태
  • 선택된 프로세스의 로그
  • 전체 프로세스의 Heap 사이즈, 사용률
  • 어플리케이션 정보

명령어:  pm2 monit

 

 

 

프로세스 무중단 재시작

As opposed to restart, which kills and restarts the process, reload achieves a 0-second-downtime reload.

 

프로세스를 죽이거나 재시작하는 restart과 달리, 0초의 다운타임이 걸리는 reload를 할 수 있다.

명령어: pm2 reload all | app-name | process-id

 

 

메모리 limit 재시작

프로세스가 정한 메모리를 넘어서면 자동으로 reload 할 수 있다.

// ecosystem.config.js
module.exports = {
  apps : [{
    script    : "app.js", 
    instances : "max", 
    exec_mode : "cluster",
    max_memory_restart: '300M' // 프로세스의 메모리가 300MB에 도달하면 reload 실행
  }]
}

 

 

 

Reference

https://engineering.linecorp.com/ko/blog/pm2-nodejs/#PM2%EB%A5%BC%ED%99%9C%EC%9A%A9%ED%95%9CNode.js%EB%AC%B4%EC%A4%91%EB%8B%A8%EC%84%9C%EB%B9%84%EC%8A%A4%ED%95%98%EA%B8%B0-%EC%84%9C%EB%B9%84%EC%8A%A4%EC%9A%B4%EC%98%81%ED%95%98%EA%B8%B0

https://armadillo-dev.github.io/javascript/nodejs/node-js-pm2/