4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VS CodeでNode.jsのクラスタ化されたサーバをデバッグする

Posted at

概要

Node.jsで作成したサーバで、マシンスペックを最大限発揮させられるように、Clusterを使います。
そのとき、デバッグの設定を作るのに苦労しました。
なので、備忘録的にここに残したいと思います。

コード

設定ファイル

launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Cluster Server",
      "program": "${workspaceFolder}/dist/server.js",
      "autoAttachChildProcesses": true,
      "console": "internalConsole"
    }
  ]
}

autoAttachChildProcesses

デバッガの子プロセスに接続するために使用します。
true にすることで、簡単にクラスタ化されたWorkerプロセスを追跡できるようになります。
デフォルト値は false です。

console

デバッガを開く場所を指定するために使用します。
これを指定しないと、子プロセスがターミナルで開いてしまいます。
internalConsole にすることで、WorkerプロセスがMasterプロセスのコンソールに紐付けられたコンソールに開くようになります。

Masterプロセス
 |- Workerプロセス
 |- Workerプロセス
 |- Workerプロセス
 `- Workerプロセス

サーバ

server.ts
import cluster from 'cluster';
import os from 'os';

const numCPUs = os.cpus().length;

import app from "./app";

if(cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  for(let i=0; i<numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  app.listen(app.get("port"), () => {
    console.log('App is running at http://localhost:%d in %d pid', app.get("port"), process.pid);
  });
}
app.ts
import express from "express";
import bodyParser from "body-parser";

import router from './router';

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 3000);

app.use(router);

export default app;

Workerプロセスを開く

.js
cluster.fork();
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?