> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 启动 HTTP 服务器集群

> 通过 "reusePort" 选项并发运行多个 HTTP 服务器，实现多个进程共享同一端口

要并发运行多个 HTTP 服务器，可以在 `Bun.serve()` 中使用 `reusePort` 选项，该选项允许多个进程共享同一个端口。

这将自动在多个 Bun 实例之间负载均衡传入的请求。

```ts server.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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("来自 Bun #" + id + " 的问候！\n");
  },
});
```

***

<Note>
  **仅限 Linux** — Windows 和 macOS 会忽略 `reusePort` 选项。这是操作系统对
  `SO_REUSEPORT` 的限制，遗憾的是如此。
</Note>

保存文件后，在相同端口启动服务器。

底层使用了 Linux 的 `SO_REUSEPORT` 和 `SO_REUSEADDR` 套接字选项，确保多个进程之间的公平负载均衡。 [了解有关 `SO_REUSEPORT` 和 `SO_REUSEADDR` 的更多信息](https://lwn.net/Articles/542629/)

```ts cluster.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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` 模块，但这是一个更快且更受限的替代方案。
