複数の HTTP サーバーを同時に実行するには、Bun.serve() で reusePort オプションを使用して、複数のプロセスで同じポートを共有します。
これにより、複数の Bun インスタンス間で受信リクエストが自動的に負荷分散されます。
ts
import { serve } from "bun";
const id = Math.random().toString(36).slice(2);
serve({
port: process.env.PORT || 8080,
development: false,
// 同じポートを複数のプロセスで共有
// これが重要な部分です!
reusePort: true,
async fetch(request) {
return new Response("Hello from Bun #" + id + "!\n");
},
});NOTE
**Linux のみ** — Windows と macOS は `reusePort` オプションを無視します。これは残念ながら `SO_REUSEPORT` のオペレーティングシステムの制限です。ファイルを保存した後、同じポートでサーバーを起動します。
内部では、Linux の SO_REUSEPORT と SO_REUSEADDR ソケットオプションを使用して、複数のプロセス間で公平な負荷分散を確保しています。SO_REUSEPORT と SO_REUSEADDR について詳しく見る →
ts
import { spawn } from "bun";
const cpus = navigator.hardwareConcurrency; // CPU コア数
const buns = new Array(cpus);
for (let i = 0; i < cpus; i++) {
buns[i] = spawn({
cmd: ["bun", "./server.ts"],
stdout: "inherit",
stderr: "inherit",
stdin: "inherit",
});
}
function kill() {
for (const bun of buns) {
bun.kill();
}
}
process.on("SIGINT", kill);
process.on("exit", kill);Bun は node:cluster モジュールも実装していますが、これはより高速でシンプルで制限された代替手段です。