티스토리 뷰

Node.js

cluster와 pm2

mongoT 2020. 3. 5. 16:45

보통 node.js프로세스는 cpu코어 하나를 사용한다.

멀티코어 cpu를 사용하고 있을 경우 node.js는 여러 개의 cpu코어를 사용할 수 있게 해주는데

그럴 때 사용하는 것이 cluster이다.

cluster모듈은 코어 하나당 노드 프로세스를 돌아가게 할 수 있다.

 

cluster

 

자신의 PC의 cpu 코어개수 확인.

const numCPUs = require('os').cpus().length;
console.log(numCPUs); // 4

cluster에는 master 프로세스와 worker 프로세스가 있다.

master프로세스는 cpu개수만큼 워커 프로세스를 만들고, 8005번 포트에서 대기하면서

요청이 들어왔을 때 worker 프로세스에 요청을 분배한다.

const numCPUs = require('os').cpus().length;
const cluster = require('cluster');
const http = require('http');

if(cluster.isMaster){
    console.log(`master: ${process.pid}`);
    
    // CPU 개수마큼 워커를 생산
    for(let i=0; i< numCPUs; i++){
        cluster.fork();
    }
    
    // 워커가 종료되었을 때
    cluster.on('exit', (worker, code, singal)=>{
        console.log(`${worker.process.pid}: closed!`);
    })
}else{
    // 워커들이 포트에서 대기
    http.createServer((req, res) => {
        res.end(`Hi, I'm cluster`);
    }).listen(8005);
    console.log('worker: ', process.pid);
}

8005번포트에 접속하면

worker프로세스가 죽었을 때 강제로 살리도록 하고 싶다면 fork()메서드로 다시 살릴 수 있다.

프로세스 id는 바뀐다.

if(cluster.isMaster){
    console.log(`master: ${process.pid}`);
    
    // CPU 개수마큼 워커를 생산
    for(let i=0; i< numCPUs; i++){
        cluster.fork();
    }
    
    // 워커가 종료되었을 때
    cluster.on('exit', (worker, code, singal)=>{
        console.log(`${worker.process.pid}: closed!`);
        cluster.fork();
    })
}else{
    // 워커들이 포트에서 대기
    http.createServer((req, res) => {
        res.end(`Hi, I'm cluster`);
        setTimeout(()=>{
            process.exit(1);
        },1000);
    }).listen(8005);
    console.log('worker: ', process.pid);
}

pm2

pm2는 2가지 기능을 한다.

첫 번째는 서버가 켜지면 다시 켜준다. (fork)

두 번째는 멀티 프로세싱을 지원한다.

 

방금 전 예제를 pm2를 적용시켜보자. 

 

pm2설치를 설치하고 package.json을 다음처럼 변경해준다.

{
  "name": "s",
  "version": "1.0.0",
  "description": "",
  "main": "cluster.js",
  "scripts": {
    "start": "pm2 start cluster.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "pm2": "^4.2.3"
  }
}

 

서버코드도 바꿔준다.

const http = require('http');

http.createServer((req, res) => {
    console.log('바보');
    res.end(`Hi, I'm cluster`);
}).listen(8005);

 

개발을 할 경우에는 nodemon같은 모듈로 nodemon cluster.js로 노드 프로세스를 실행한다.

배포시에는 pm2 start cluster.js 명령어로 실행한다.

pm2가 노드프로세스를 백그라운드로 돌리고 있기 때문에 terminal을 계속 이용할 수 있다.

노드프로세스 list를 확인하려면 pm2를 전역으로 설치하고(npm i -g pm2)

pm2 list명령어를 입력.

pm2프로세스를 종료하고 싶다면 pm2 kill(모든 worker프로세스 종료)

코어에 맞는 개수만큼 worker 프로세스를 생성하고 싶다면

packe.json에서 명령어를 pm2 start cluster.js -i 0

-i뒤에 만들고 싶은 worker프로세스 개수를 넣어주면 되는데

0을 넣어주면 자동으로 코어개수만큼 worker프로세스를 생산한다.

{
  "name": "s",
  "version": "1.0.0",
  "description": "",
  "main": "cluster.js",
  "scripts": {
    "start": "pm2 start cluster.js -i 0"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "pm2": "^4.2.3"
  }
}

 

npm start를 해보면

쿼드코어 컴퓨터니까 worker프로세스가 4개 생성된 것을 알 수 있다.

만약 log나 현재 상태를 감시하고 싶다면 pm2 monit명령어를 사용하면된다.

const http = require('http');

http.createServer((req, res) => {
    console.log('바보');
    res.end(`Hi, I'm cluster`);
}).listen(8005);

 

옆에 cluster logs로 log를 확인할 수 있다.

 

다시 로드하고 싶으면 pm2 reload all | [processId]

 

참고문헌: node.js교과서

node.js 레퍼런스: https://nodejs.org/dist/latest-v12.x/docs/api/cluster.html#cluster_cluster_ismaster

pm2 레퍼런스: https://www.npmjs.com/package/pm2

'Node.js' 카테고리의 다른 글

resave와 saveUnitialized  (0) 2020.03.22
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함