bun-deploy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bun 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+个优化模板
  • Kuberneteskubernetes.md - K8s清单、HPA、Ingress
  • CI/CDci-cd.md - GitHub Actions、GitLab CI、构建脚本
  • 多平台构建multi-platform.md - ARM64/AMD64架构构建

Core Workflow

核心工作流程

1. Check Prerequisites

1. 检查前置条件

bash
undefined
bash
undefined

Verify 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
undefined
ls -la package.json bun.lockb
undefined

2. 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
undefined

syntax=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
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", "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
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", "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.yml
dockerignore
node_modules
bun.lockb
dist
*.log
.git
.env
.env.local
tests/
*.test.ts
coverage/
.vscode/
.DS_Store
Dockerfile
docker-compose.yml

5. Create Health Check Script

5. 创建健康检查脚本

Create
healthcheck.ts
:
typescript
#!/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.ts
typescript
#!/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
undefined
bash
undefined

Build 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

7. Setup for Environment

7. 适配目标环境

For Local Development with Docker Compose:
Create
docker-compose.yml
:
yaml
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 up
For 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.yml
yaml
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 up
Kubernetes部署:
查看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:
ConfigurationSizeUse Case
Bun Binary (distroless)~40 MBProduction (minimal)
Bun Alpine~90 MBProduction (standard)
Node.js Alpine~180 MBBaseline 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

安全最佳实践

  1. Use non-root user (included in Dockerfiles above)
  2. Scan for vulnerabilities:
    docker scan myapp:latest
  3. Use official base images:
    oven/bun
    is official
  4. Keep images updated: Rebuild regularly with latest Bun
  5. Never hardcode secrets: Use environment variables or secret managers
  1. 使用非root用户(上述Dockerfile已包含)
  2. 漏洞扫描
    docker scan myapp:latest
  3. 使用官方基础镜像
    oven/bun
    为官方镜像
  4. 保持镜像更新:定期使用最新版Bun重建镜像
  5. 切勿硬编码密钥:使用环境变量或密钥管理工具

Optimization Tips

优化技巧

Layer caching:
dockerfile
undefined
分层缓存:
dockerfile
undefined

Copy 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:**
```dockerfile
COPY . . RUN bun run build

**减少镜像层数:**
```dockerfile

Combine RUN commands

Combine RUN commands

RUN bun install &&
bun run build &&
rm -rf tests/

**Minimize final image:**
```dockerfile
RUN bun install &&
bun run build &&
rm -rf tests/

**最小化最终镜像:**
```dockerfile

Only 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)

undefined
undefined

Completion 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:
  1. Monitoring: Add Prometheus metrics endpoint
  2. Logging: Configure structured logging
  3. Secrets: Set up proper secret management
  4. Scaling: Configure horizontal pod autoscaling (K8s)
  5. CI/CD: Automate builds and deployments
  6. Multi-region: Deploy to multiple regions for redundancy
For detailed implementations, see the reference files linked above.
基础部署完成后:
  1. 监控:添加Prometheus指标端点
  2. 日志:配置结构化日志
  3. 密钥管理:设置专业的密钥管理方案
  4. 扩缩容:配置水平Pod自动扩缩容(K8s)
  5. CI/CD:自动化构建与部署流程
  6. 多区域部署:部署到多个区域以实现冗余
如需详细实现,请查看上方链接的参考文档。