Salta al contenuto principale

Bun production deployment: Docker + Kubernetes

Bun in produzione con Docker e Kubernetes: Dockerfile multi-stage, build e push dell'immagine, manifest YAML, health check, risorse e rolling update.

Cosa ne pensi di questo articolo?

Bun production deployment: Docker + Kubernetes
Bun Runtime 2027Foto:panumas nikhomkhaiPexels

In Breve

Bun in produzione con Docker e Kubernetes: Dockerfile multi-stage, build e push dell'immagine, manifest YAML, health check, risorse e rolling update.

Deployare Bun in produzione con Docker e Kubernetes richiede 8 pattern combinati: multi-stage Docker builds ottimizzati per Bun, health checks robusti, resource limits e readiness probe, load balancing con NGINX ingress, secret management per env vars, rolling update strategy con disruption budget, monitoring di memoria e velocità, e graceful shutdown di runtime JavaScript. Questo articolo documenta le best practice testate per scalare applicazioni Bun da staging a produzione su cluster Kubernetes.

Introduzione: Bun in Produzione

Bun è un runtime JavaScript moderno e veloce, costruito su Zig, che promette performance 3-4x superiori a Node.js per applicazioni I/O intensive e startup time critico. Tuttavia, deployare Bun in produzione con Docker e Kubernetes presenta sfide uniche: il runtime è relativamente nuovo, la community è in crescita, e molti tutorial online si fermano al "containerizzare Node.js". Questa guida documenta un workflow production-grade testato su cluster Kubernetes su VPS con ingress Nginx, utilizzo di Bun 1.1.14+, e applicazioni Elysia/Hono framerate.

Chi dovrebbe leggere questo articolo: backend engineer con esperienza Docker + Kubernetes che vuole esplorare Bun per nuovi microservizi, oppure engineering team che valuta migrazioni da Node.js a Bun. Presupposto: familiarità con Kubernetes YAML, kubectl, e flusso di deployment tipico (build → push → apply manifests).

Cos'è Bun e Perché Containerizzarlo

Bun è un runtime JavaScript tutto-in-uno che include package manager (bun install), test runner (bun test), transpiler built-in, e Web API support. A differenza di Node.js, Bun è scritto in Zig (linguaggio low-level) e compila il codice JavaScript in binario ottimizzato. Perché containerizzarlo in produzione?

  • Isolamento di ambiente: Bun ha dipendenze di sistema (librerie C, SSL certs) che variando da macchina a macchina. Docker garantisce che app + runtime + deps vivono nello stesso container reproducibile.
  • Orchestrazione Kubernetes: In produzione, serve schedulare pod, gestire resource limits, restart automatici, e rolling update senza downtime. Kubernetes fa tutto questo via container images.
  • Scaling orizzontale: Molteplici replicas del container girano su nodi diversi del cluster, bilanciati da NGINX ingress controller o Istio.
  • Security: Container di Bun girano in user unprivileged, con read-only filesystem, network policies, e secret mount encrypts via etcd.

Setup Ambiente Locale: Bun + Docker

Prima di deployare su Kubernetes, configura un ambiente locale per testare l'app Bun e l'immagine Docker.

Passo 1: Installare Bun Localmente


# macOS / Linux
curl -fsSL https://bun.sh/install | bash

# Verifica
bun --version    # e.g., bun 1.1.14

# Crea progetto di esempio (Hono framework)
bun create hono myapp
cd myapp
bun install

Passo 2: Scrivere un'App Hono Semplice


// src/index.ts
import { Hono } from 'hono';

const app = new Hono();

app.get('/', (c) => c.json({ message: 'Hello Bun on K8s!' }));

app.get('/health', (c) => c.json({ status: 'healthy', uptime: process.uptime() }));

app.post('/api/echo', async (c) => {
  const body = await c.req.json();
  return c.json({ echo: body });
});

export default app;

Passo 3: Configurare package.json con Start Script


{
  "name": "bun-app",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "bun --watch src/index.ts",
    "start": "bun src/index.ts",
    "build": "bun build ./src/index.ts --target bun --outdir ./dist"
  },
  "dependencies": {
    "hono": "^4.0.0"
  }
}

Passo 4: Test Locale


# Avvia app Bun
bun start &
# Oppure
bun run dev

# In un'altro terminale, testa endpoint
curl http://localhost:3000/
curl http://localhost:3000/health

# Ctrl+C per fermare

Containerizzazione: Multi-Stage Dockerfile Ottimizzato

La chiave per un'immagine Docker leggera e veloce è il multi-stage build: scarica dipendenze nella build stage, copia solo l'app transpilata nella run stage, riducendo la size finale.

Dockerfile per Bun


# Stage 1: Builder
FROM oven/bun:1.1.14-alpine AS builder

WORKDIR /build

# Copia package.json/lock
COPY package.json bun.lockb* ./

# Installa dipendenze
RUN bun install --frozen-lockfile

# Copia source
COPY src ./src

# Build (opzionale se usi direct run)
RUN bun build ./src/index.ts --target bun --outdir ./dist

# Stage 2: Runtime
FROM oven/bun:1.1.14-alpine

WORKDIR /app

# Non-root user per security
RUN addgroup -g 1001 -S bun && \
    adduser -S bun -u 1001

# Copia da builder
COPY --from=builder --chown=bun:bun /build/node_modules ./node_modules
COPY --from=builder --chown=bun:bun /build/package.json ./
COPY --from=builder --chown=bun:bun /build/src ./src

# Cambio user
USER bun

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD bun run src/health.ts || exit 1

# Start app
CMD ["bun", "start"]

Script Health Check (src/health.ts)


// src/health.ts - per healthcheck in Dockerfile
const response = await fetch('http://localhost:3000/health');
const data = await response.json();
if (data.status === 'healthy') {
  process.exit(0);
} else {
  process.exit(1);
}

Build e Push Image su Registry

Dopo il Dockerfile, compila l'immagine e pushala su container registry (Docker Hub, GitHub Container Registry, o registry privato Kubernetes).


# Build image locale
docker build -t myapp:1.0.0 .
docker build -t myapp:latest .

# Tag per registry (es. GitHub Container Registry)
docker tag myapp:1.0.0 ghcr.io/fedcal/myapp:1.0.0
docker tag myapp:latest ghcr.io/fedcal/myapp:latest

# Login registry (se privato)
echo $GH_PAT | docker login ghcr.io -u fedcal --password-stdin

# Push
docker push ghcr.io/fedcal/myapp:1.0.0
docker push ghcr.io/fedcal/myapp:latest

# Verifica image su registry
curl https://ghcr.io/v2/fedcal/myapp/tags/list

Kubernetes Deployment: Manifests YAML

Ora definiamo i Kubernetes objects per deployare l'app Bun sul cluster.

Deployment YAML (deployment.yaml)


apiVersion: apps/v1
kind: Deployment
metadata:
  name: bun-app
  namespace: production
  labels:
    app: bun-app
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: bun-app
  template:
    metadata:
      labels:
        app: bun-app
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "3000"
        prometheus.io/path: "/metrics"
    spec:
      securityContext:
        fsGroup: 1001
        runAsNonRoot: true
      containers:
      - name: bun
        image: ghcr.io/fedcal/myapp:latest
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
          name: http
        env:
        - name: NODE_ENV
          value: "production"
        - name: LOG_LEVEL
          value: "info"
        - name: PORT
          value: "3000"
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: bun-app-secrets
              key: database-url
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 10
          periodSeconds: 30
          timeoutSeconds: 3
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 5
          periodSeconds: 10
          timeoutSeconds: 2
          failureThreshold: 2
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop:
            - ALL
        volumeMounts:
        - name: tmp
          mountPath: /tmp
      volumes:
      - name: tmp
        emptyDir: {}
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - bun-app
              topologyKey: kubernetes.io/hostname

Service YAML (service.yaml)


apiVersion: v1
kind: Service
metadata:
  name: bun-app-service
  namespace: production
spec:
  type: ClusterIP
  selector:
    app: bun-app
  ports:
  - port: 80
    targetPort: 3000
    protocol: TCP
    name: http
  sessionAffinity: None

Ingress YAML (ingress.yaml)


apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: bun-app-ingress
  namespace: production
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rate-limit: "100"
spec:
  tls:
  - hosts:
    - myapp.example.com
    secretName: bun-app-tls
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: bun-app-service
            port:
              number: 80

Secret Management: Gestire Variabili di Ambiente

Non hardcodare secrets nel Deployment YAML. Crea un Secret Kubernetes:


# Crea secret da env file
kubectl create secret generic bun-app-secrets \
  --from-literal=database-url="postgres://user:pass@db:5432/mydb" \
  --namespace=production

# Oppure da file
kubectl create secret generic bun-app-secrets \
  --from-file=.env.production \
  --namespace=production

# Verifica
kubectl get secrets -n production
kubectl describe secret bun-app-secrets -n production

Deploy su Kubernetes Cluster

Applica i manifests al cluster:


# Applica Deployment, Service, Ingress
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f ingress.yaml

# Verifica pod in running
kubectl get pods -n production -w
kubectl logs -f deployment/bun-app -n production

# Test ingress da fuori cluster
curl https://myapp.example.com/health

Monitoring e Logging

In produzione, monitora memoria, CPU, request latency e error rate dell'app Bun.

Prometheus Metrics (opzionale ma consigliato)

Aggiungi un endpoint `/metrics` all'app per esporre metriche Prometheus:


// src/index.ts - aggiungi endpoint metrics
import { Hono } from 'hono';

const app = new Hono();

// Counter di requests
let requestCount = 0;

app.use('*', (c, next) => {
  requestCount++;
  return next();
});

app.get('/metrics', (c) => {
  const metrics = `
# HELP requests_total Total HTTP requests
# TYPE requests_total counter
requests_total{app="bun-app"} ${requestCount}

# HELP process_memory_bytes Memory usage
# TYPE process_memory_bytes gauge
process_memory_bytes ${process.memoryUsage().heapUsed}
  `.trim();
  return c.text(metrics, 200, { 'Content-Type': 'text/plain' });
});

export default app;

Logging Strutturato


// src/logger.ts
export function log(level: string, message: string, meta?: any) {
  const timestamp = new Date().toISOString();
  console.log(JSON.stringify({
    timestamp,
    level,
    message,
    ...(meta && { meta })
  }));
}

// Uso
log('info', 'Server started', { port: 3000 });
log('error', 'DB connection failed', { error: 'ECONNREFUSED' });

Best Practices e Troubleshooting

Best Practices

  • Resource Limits: Sempre definire requests/limits di CPU e memoria (vedi Deployment YAML sopra).
  • Graceful Shutdown: Intercetta SIGTERM in Hono per chiudere connessioni DB prima di terminare.
  • Health Checks: Endpoint `/health` che ritorna 200 OK se l'app è pronta, 500 se no.
  • Rolling Updates: Strategy RollingUpdate con maxSurge=1 e maxUnavailable=0 garantisce zero-downtime deploys.
  • Pod Disruption Budgets: Se usi cluster autoscaling, definisci PodDisruptionBudget per evitare eviction di tutti i pod simultaneamente.

Troubleshooting Comune

Pod Pending o CrashLoopBackOff: Controlla logs con `kubectl logs -f deployment/bun-app`. Spesso è resource limit o missing secret.

Lentezza dopo deploy: Bun al first startup compila e JIT-compila codice. Spike di CPU è normale nei primi 10-30 secondi. Aumenta initialDelaySeconds della liveness probe se necessario.

Memory leak: Se l'app cresce in memoria nel tempo, controlla for loop che non dealloca, oppure connection pool non chiuso. Usa `bun --profile` localmente per profiling.

FAQ

Posso usare Bun con Express.js anziché Hono?

Sì, Bun è compatibile con Express, ma Express è ottimizzato per Node.js. Hono (o Elysia) sono scritti per Bun-first ed hanno performance migliore.

Bun in produzione è stabile?

Bun 1.1.0+ è sufficientemente stabile per workload production, ma è ancora in active development (1.x non è 2.0). Monitora breaking changes tra minor release.

Come faccio a fare deploy zero-downtime?

Usa Deployment con RollingUpdate strategy (maxUnavailable: 0). Kubernetes termina un pod vecchio solo dopo che il nuovo è readiness-passed.

Posso usare Bun con serverless (AWS Lambda, Google Cloud Run)?

Parzialmente. Bun 1.0+ supporta AWS Lambda custom runtime, ma il setup è complesso. Per serverless classico, Node.js 20+ è ancora più maturo.

Quali sono i runtime alternatives a Bun?

Node.js (runtime di riferimento), Deno (altro runtime alternativo, runtime Deno API standard però diversa da Node), e Vercel Edge Runtime (serverless only).

Commenti

Caricamento commenti...

Accedi per commentare

Discuti questo articolo nella community

Unisciti al gruppo Telegram per discutere con altri sviluppatori, fare domande e condividere le tue esperienze.

Ti è piaciuto questo articolo?

Esplora altri contenuti sul blog o scopri i miei progetti