bun-deploy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBun Docker Deployment
Bun Docker 部署
Create optimized Docker images for Bun applications. Bun's small runtime and binary compilation reduce image sizes by 88MB+ compared to Node.js.
为Bun应用创建优化的Docker镜像。与Node.js相比,Bun的轻量运行时和二进制编译特性可将镜像体积减少88MB以上。
Quick Reference
快速参考
For detailed patterns, see:
- Dockerfile Templates: dockerfile-templates.md - 12+ optimized templates
- Kubernetes: kubernetes.md - K8s manifests, HPA, ingress
- CI/CD: ci-cd.md - GitHub Actions, GitLab CI, build scripts
- Multi-Platform: multi-platform.md - ARM64/AMD64 builds
如需详细实现方案,请查看:
- Dockerfile模板:dockerfile-templates.md - 12+个优化模板
- Kubernetes:kubernetes.md - K8s清单、HPA、Ingress
- CI/CD:ci-cd.md - GitHub Actions、GitLab CI、构建脚本
- 多平台构建:multi-platform.md - ARM64/AMD64架构构建
Core Workflow
核心工作流程
1. Check Prerequisites
1. 检查前置条件
bash
undefinedbash
undefinedVerify Docker is installed
Verify Docker is installed
docker --version
docker --version
Verify Bun is installed locally
Verify Bun is installed locally
bun --version
bun --version
Check if project is ready for deployment
Check if project is ready for deployment
ls -la package.json bun.lockb
undefinedls -la package.json bun.lockb
undefined2. Determine Deployment Strategy
2. 确定部署策略
Ask the user about their needs:
- Application Type: Web server, API, worker, or CLI
- Image Size Priority: Minimal size (40MB binary) vs. debugging tools (90MB Alpine)
- Platform: Single platform or multi-platform (AMD64 + ARM64)
- Orchestration: Docker Compose, Kubernetes, or standalone containers
询问用户的需求:
- 应用类型:Web服务器、API、工作进程或CLI工具
- 镜像体积优先级:极简体积(40MB二进制)vs. 带调试工具(90MB Alpine镜像)
- 平台架构:单一平台或多平台(AMD64 + ARM64)
- 编排工具:Docker Compose、Kubernetes或独立容器
3. Create Production Dockerfile
3. 创建生产环境Dockerfile
Choose the appropriate template based on needs:
Standard Multi-Stage (Recommended)
dockerfile
undefined根据需求选择合适的模板:
标准多阶段构建(推荐)
dockerfile
undefinedsyntax=docker/dockerfile:1
syntax=docker/dockerfile:1
FROM oven/bun:1-alpine AS deps
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production
FROM oven/bun:1-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN bun run build
FROM oven/bun:1-alpine AS runtime
WORKDIR /app
RUN addgroup --system --gid 1001 bunuser &&
adduser --system --uid 1001 bunuser
adduser --system --uid 1001 bunuser
COPY --from=deps --chown=bunuser:bunuser /app/node_modules ./node_modules
COPY --from=builder --chown=bunuser:bunuser /app/dist ./dist
COPY --from=builder --chown=bunuser:bunuser /app/package.json ./
USER bunuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3
CMD bun run healthcheck.ts || exit 1
CMD bun run healthcheck.ts || exit 1
CMD ["bun", "run", "dist/index.js"]
**Minimal Binary (40MB)**
For smallest possible images:
```dockerfile
FROM oven/bun:1-alpine AS builder
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun build ./src/index.ts --compile --outfile server
FROM gcr.io/distroless/base-debian12
COPY --from=builder /app/server /server
EXPOSE 3000
ENTRYPOINT ["/server"]For other scenarios (monorepo, database apps, CLI tools, etc.), see dockerfile-templates.md.
FROM oven/bun:1-alpine AS deps
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production
FROM oven/bun:1-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN bun run build
FROM oven/bun:1-alpine AS runtime
WORKDIR /app
RUN addgroup --system --gid 1001 bunuser &&
adduser --system --uid 1001 bunuser
adduser --system --uid 1001 bunuser
COPY --from=deps --chown=bunuser:bunuser /app/node_modules ./node_modules
COPY --from=builder --chown=bunuser:bunuser /app/dist ./dist
COPY --from=builder --chown=bunuser:bunuser /app/package.json ./
USER bunuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3
CMD bun run healthcheck.ts || exit 1
CMD bun run healthcheck.ts || exit 1
CMD ["bun", "run", "dist/index.js"]
**极简二进制镜像(40MB)**
用于追求最小镜像体积的场景:
```dockerfile
FROM oven/bun:1-alpine AS builder
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun build ./src/index.ts --compile --outfile server
FROM gcr.io/distroless/base-debian12
COPY --from=builder /app/server /server
EXPOSE 3000
ENTRYPOINT ["/server"]其他场景(单体仓库、数据库应用、CLI工具等),请查看dockerfile-templates.md。
4. Create .dockerignore
4. 创建.dockerignore文件
dockerignore
node_modules
bun.lockb
dist
*.log
.git
.env
.env.local
tests/
*.test.ts
coverage/
.vscode/
.DS_Store
Dockerfile
docker-compose.ymldockerignore
node_modules
bun.lockb
dist
*.log
.git
.env
.env.local
tests/
*.test.ts
coverage/
.vscode/
.DS_Store
Dockerfile
docker-compose.yml5. Create Health Check Script
5. 创建健康检查脚本
Create :
healthcheck.tstypescript
#!/usr/bin/env bun
const port = process.env.PORT || 3000;
const healthEndpoint = process.env.HEALTH_ENDPOINT || '/health';
try {
const response = await fetch(`http://localhost:${port}${healthEndpoint}`, {
method: 'GET',
timeout: 2000,
});
if (response.ok) {
process.exit(0);
} else {
console.error(`Health check failed: ${response.status}`);
process.exit(1);
}
} catch (error) {
console.error('Health check error:', error);
process.exit(1);
}Add health endpoint to your server:
typescript
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: Date.now(),
uptime: process.uptime(),
});
});创建:
healthcheck.tstypescript
#!/usr/bin/env bun
const port = process.env.PORT || 3000;
const healthEndpoint = process.env.HEALTH_ENDPOINT || '/health';
try {
const response = await fetch(`http://localhost:${port}${healthEndpoint}`, {
method: 'GET',
timeout: 2000,
});
if (response.ok) {
process.exit(0);
} else {
console.error(`Health check failed: ${response.status}`);
process.exit(1);
}
} catch (error) {
console.error('Health check error:', error);
process.exit(1);
}在服务器中添加健康检查端点:
typescript
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: Date.now(),
uptime: process.uptime(),
});
});6. Build and Test Image
6. 构建并测试镜像
bash
undefinedbash
undefinedBuild image
Build image
docker build -t myapp:latest .
docker build -t myapp:latest .
Check image size
Check image size
docker images myapp:latest
docker images myapp:latest
Run container
Run container
docker run -p 3000:3000 myapp:latest
docker run -p 3000:3000 myapp:latest
Test health endpoint
Test health endpoint
undefinedundefined7. Setup for Environment
7. 适配目标环境
For Local Development with Docker Compose:
Create :
docker-compose.ymlyaml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
- NODE_ENV=development
depends_on:
- db
- redis
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
ports:
- "5432:5432"
redis:
image: redis:7-alpine
ports:
- "6379:6379"Run with:
docker-compose upFor Kubernetes Deployment:
See kubernetes.md for complete manifests including:
- Deployment configuration
- Service and Ingress
- Secrets and ConfigMaps
- Horizontal Pod Autoscaling
- Resource limits optimized for Bun
For CI/CD:
See ci-cd.md for:
- GitHub Actions workflow
- GitLab CI configuration
- Build and push scripts
- Automated deployments
For Multi-Platform (ARM64 + AMD64):
See multi-platform.md for:
- Multi-platform Dockerfile
- Buildx configuration
- Testing on different architectures
本地开发(使用Docker Compose):
创建:
docker-compose.ymlyaml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
- NODE_ENV=development
depends_on:
- db
- redis
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
ports:
- "5432:5432"
redis:
image: redis:7-alpine
ports:
- "6379:6379"启动命令:
docker-compose upKubernetes部署:
查看kubernetes.md获取完整清单,包括:
- 部署配置
- Service与Ingress
- Secrets与ConfigMaps
- 水平Pod自动扩缩容
- 为Bun优化的资源限制
CI/CD配置:
查看ci-cd.md获取:
- GitHub Actions工作流
- GitLab CI配置
- 构建与推送脚本
- 自动化部署流程
多平台构建(ARM64 + AMD64):
查看multi-platform.md获取:
- 多平台Dockerfile
- Buildx配置
- 跨架构测试方法
8. Update package.json
8. 更新package.json
Add Docker scripts:
json
{
"scripts": {
"docker:build": "docker build -t myapp:latest .",
"docker:run": "docker run -p 3000:3000 myapp:latest",
"docker:dev": "docker-compose up",
"docker:clean": "docker system prune -af"
}
}添加Docker相关脚本:
json
{
"scripts": {
"docker:build": "docker build -t myapp:latest .",
"docker:run": "docker run -p 3000:3000 myapp:latest",
"docker:dev": "docker-compose up",
"docker:clean": "docker system prune -af"
}
}Image Size Comparison
镜像体积对比
Bun produces significantly smaller images:
| Configuration | Size | Use Case |
|---|---|---|
| Bun Binary (distroless) | ~40 MB | Production (minimal) |
| Bun Alpine | ~90 MB | Production (standard) |
| Node.js Alpine | ~180 MB | Baseline comparison |
88MB+ savings with Bun!
Bun生成的镜像体积显著更小:
| 配置 | 大小 | 适用场景 |
|---|---|---|
| Bun Binary (distroless) | ~40 MB | 生产环境(极简版) |
| Bun Alpine | ~90 MB | 生产环境(标准版) |
| Node.js Alpine | ~180 MB | 基准对比 |
使用Bun可节省88MB以上的空间!
Security Best Practices
安全最佳实践
- Use non-root user (included in Dockerfiles above)
- Scan for vulnerabilities:
docker scan myapp:latest - Use official base images: is official
oven/bun - Keep images updated: Rebuild regularly with latest Bun
- Never hardcode secrets: Use environment variables or secret managers
- 使用非root用户(上述Dockerfile已包含)
- 漏洞扫描:
docker scan myapp:latest - 使用官方基础镜像:为官方镜像
oven/bun - 保持镜像更新:定期使用最新版Bun重建镜像
- 切勿硬编码密钥:使用环境变量或密钥管理工具
Optimization Tips
优化技巧
Layer caching:
dockerfile
undefined分层缓存:
dockerfile
undefinedCopy dependencies first (changes less often)
Copy dependencies first (changes less often)
COPY package.json bun.lockb ./
RUN bun install
COPY package.json bun.lockb ./
RUN bun install
Copy source code last (changes more often)
Copy source code last (changes more often)
COPY . .
RUN bun run build
**Reduce layer count:**
```dockerfileCOPY . .
RUN bun run build
**减少镜像层数:**
```dockerfileCombine RUN commands
Combine RUN commands
RUN bun install &&
bun run build &&
rm -rf tests/
bun run build &&
rm -rf tests/
**Minimize final image:**
```dockerfileRUN bun install &&
bun run build &&
rm -rf tests/
bun run build &&
rm -rf tests/
**最小化最终镜像:**
```dockerfileOnly copy what's needed in runtime
Only copy what's needed in runtime
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/dist ./dist
Don't copy: src/, tests/, .git/, node_modules (if using binary)
Don't copy: src/, tests/, .git/, node_modules (if using binary)
undefinedundefinedCompletion Checklist
完成检查清单
- ✅ Dockerfile created (multi-stage or binary)
- ✅ .dockerignore configured
- ✅ Health check implemented
- ✅ Non-root user configured
- ✅ Image built and tested locally
- ✅ Image size verified (<100MB for Alpine, <50MB for binary)
- ✅ Environment configuration ready (docker-compose or K8s)
- ✅ CI/CD pipeline configured (if needed)
- ✅ 已创建Dockerfile(多阶段或二进制构建)
- ✅ 已配置.dockerignore
- ✅ 已实现健康检查
- ✅ 已配置非root用户
- ✅ 已在本地构建并测试镜像
- ✅ 已验证镜像体积(Alpine版<100MB,二进制版<50MB)
- ✅ 已准备好环境配置(docker-compose或K8s)
- ✅ 已配置CI/CD流水线(如有需要)
Next Steps
后续步骤
After basic deployment:
- Monitoring: Add Prometheus metrics endpoint
- Logging: Configure structured logging
- Secrets: Set up proper secret management
- Scaling: Configure horizontal pod autoscaling (K8s)
- CI/CD: Automate builds and deployments
- Multi-region: Deploy to multiple regions for redundancy
For detailed implementations, see the reference files linked above.
基础部署完成后:
- 监控:添加Prometheus指标端点
- 日志:配置结构化日志
- 密钥管理:设置专业的密钥管理方案
- 扩缩容:配置水平Pod自动扩缩容(K8s)
- CI/CD:自动化构建与部署流程
- 多区域部署:部署到多个区域以实现冗余
如需详细实现,请查看上方链接的参考文档。