10.1 官方 Docker 镜像
Bun 提供官方镜像 oven/bun:
| tag | 说明 | 体积 |
|---|---|---|
oven/bun:1 | 最新 stable,基于 Debian | ~120MB |
oven/bun:1-slim | 瘦身版 Debian | ~80MB |
oven/bun:1-alpine | Alpine(实验,小但 DNS 等有差异) | ~55MB |
oven/bun:1-distroless | 无 shell,极简,安全 | ~60MB |
oven/bun:canary | 每日构建 |
10.2 最小 Dockerfile
FROM oven/bun:1 AS base
WORKDIR /app
# 先装依赖(层缓存)
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
# 拷贝源码
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
CMD ["bun", "src/server.ts"]
10.3 多阶段构建:只留产物
FROM oven/bun:1 AS builder
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun build src/server.ts --target=bun --outdir dist
FROM oven/bun:1-distroless
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["bun", "dist/server.js"]
10.4 --smol:低内存模式
容器跑在内存受限环境(Cloud Run、Fly.io、低配 VPS)时加 --smol:
CMD ["bun", "--smol", "dist/server.js"]
效果:使用更激进的 GC,牺牲少量吞吐换取更低的驻留内存(RSS 降低 30-50%)。
10.5 多进程:node:cluster
要利用多核:
import cluster from "node:cluster";
import os from "node:os";
if (cluster.isPrimary) {
for (let i = 0; i < os.availableParallelism(); i++) {
cluster.fork();
}
cluster.on("exit", (w) => {
console.error(`worker ${w.process.pid} died, restarting`);
cluster.fork();
});
} else {
await import("./server.ts");
}
Bun 1.2 起 Bun.serve 支持 reusePort: true 让多进程共享端口,内核层面负载均衡。
10.6 docker-compose 示例
services:
api:
image: my-api:latest
build: .
ports: ["3000:3000"]
env_file: .env.production
restart: unless-stopped
deploy:
resources:
limits: { cpus: '1.0', memory: 512M }
redis:
image: redis:7-alpine
restart: unless-stopped
10.7 健康检查
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
CMD bun -e 'fetch("http://localhost:3000/health").then(r=>process.exit(r.ok?0:1))' || exit 1
10.8 生态框架
ElysiaJS
TS 原生、端到端类型安全、插件生态丰富,类 tRPC + Hono 的组合体:
import { Elysia, t } from "elysia";
const app = new Elysia()
.get("/", () => "hi")
.post("/users", ({ body }) => ({ created: body }), {
body: t.Object({ name: t.String(), age: t.Number() }),
})
.listen(3000);
export type App = typeof app; // 客户端可复用这个类型
Hono
多运行时(Bun/Node/Deno/Workers/Lambda),极简 API:
import { Hono } from "hono";
const app = new Hono()
.get("/", (c) => c.text("hi"))
.get("/json", (c) => c.json({ hello: "world" }));
export default { port: 3000, fetch: app.fetch };
其他值得关注
- Drizzle ORM:与 bun:sqlite/Postgres 完美整合
- Auth.js:认证通用
- Better Auth:Bun/Hono 友好
- Vitest / @bun-test/...:若想 Vitest 生态 + Bun 运行时
10.9 监控与观测
OpenTelemetry 支持已有,但成熟度低于 Node。生产推荐:
- Sentry:JS SDK 跑在 Bun 上没问题
- pino:超快 JSON logger,Bun 上兼容
- prom-client:Prometheus 指标
- Bun --profile:CPU 采样
10.10 何时选 Bun(决策清单)
强烈推荐
- 新项目,需求里有 TS + 高吞吐 API
- 边缘/Serverless 函数(冷启动快)
- 本地 CLI / 脚本(Bun Shell + --compile)
- 内部工具(发单文件二进制)
- 测试加速(bun test 替代 jest)
谨慎评估
- 重度依赖 V8 特性的项目(profiler/snapshot)
- Next.js 生产(兼容性改进中,优先看 Bun 官方状态)
- 深度集成 node-gyp 原生模块的老项目
先别换
- 完全稳定运行的 Node 老系统——收益有限,迁移风险不必要
10.11 全书总结
- Bun 是 Zig 写的一体化 JS 工具链:运行时 + 包管理 + 打包 + 测试,一个二进制搞定。
- 核心命令:
bun install(快 25×)、bun run(快 150×)、bun test(快 100×)、bun build。 - HTTP/WebSocket 用
Bun.serve(Web 标准 API,3× Node 吞吐);内置 Bun.file / bun:sqlite / bun:redis / Bun.password / Bun.spawn。 - Node API ~95%+ 兼容,Express/Fastify 直接跑;渐进用 Bun 原生 API 加速。
- FFI 直接调 C 库 +
bun build --compile单文件可执行——分发利器。 - 生产容器:
oven/bun+ multi-stage +--smol+ cluster 或 reusePort 多进程。
至此 10 章内容完成。Bun 正在重塑整条 JavaScript 工具链——越早用越享受启动秒级、测试毫秒级、部署单文件的现代体验。