여러 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 모듈도 구현했지만 이것은 더 빠르고 간단하며 제한적인 대안입니다.