部署 Fastify 应用
高性能 Node.js 框架,基于 schema 序列化,通过 PM2、Docker 或 serverless 部署。
平台进阶
为什么
Fastify 比 Express 快 2-3 倍,得益于 JSON schema 序列化和编译。插件架构和内置 TypeScript 支持使其适合性能关键 API。
平台即服务采用率 2024 年增长 24%,团队从虚拟机管理转向 git push 部署。the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research),PaaS 层捕获了大多数新工作负载。
何时使用
吞吐量重要时(高流量 API、网关)选 Fastify 而非 Express。中间件生态兼容性更重要时用 Express。
如何做
1. 构建 — tsc 编译,fastify 本身无构建步骤
2. Schema — 路由定义 JSON schema,fastify 编译快速序列化
3. PM2 — pm2 start dist/server.js -i max 集群
4. Docker — node:20-alpine,CMD ["node", "dist/server.js"]
5. Serverless — @fastify/aws-lambda 适配 Lambda
6. 插件 — fastify.register() 注册,封装作用域
7. 钩子 — onRequest/preHandler 鉴权、日志、指标
示例
// src/server.ts — Fastify 带 schema
import Fastify from "fastify";
const app = Fastify({ logger: true });
app.get("/users/:id", {
schema: {
params: { type: "object", properties: { id: { type: "string" } } },
response: { 200: { type: "object", properties: { id: { type: "string" }, name: { type: "string" } } } },
},
handler: async (req) => ({ id: req.params.id, name: "Alice" }),
});
app.listen({ port: 3000, host: "0.0.0.0" });
// Dockerfile
FROM node:20-alpine AS build
WORKDIR /app
COPY . .
RUN npm ci && npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]
常见问题
- ⚠Schema 验证拒绝合法数据 — schema 过严,有意加 additionalProperties: false
- ⚠插件作用域问题 — 装饰器在封装插件作用域外不可用,用 fastify-plugin
- ⚠无 schema 序列化慢 — 无 schema 响应用慢 JSON.stringify,始终定义响应 schema
最佳实践
- ✓始终为路由定义 JSON schema — Fastify 速度来自 schema 编译序列化
- ✓装饰器需全局可用时用 fastify-plugin 打破封装
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求