引言
小团队常把 Kubernetes 当作容器编排的默认答案,但它的运维成本可能超过业务本身。多服务应用可以先在 Compose 上获得大部分收益。
为什么暂不上 Kubernetes
Kubernetes 解决的是大规模调度、滚动发布和多租户资源管理。服务数量少、流量可预测时,这些能力用不上,而控制平面、网络和权限的复杂度却立即出现。
Compose 与健康检查
一个 docker-compose.yml 定义应用、数据库和缓存,共享网络和环境变量。健康检查让依赖就绪后再启动应用,避免启动竞态;应用自身仍要重试连接。
资源与关闭
为容器设置内存和 CPU 限制,防止单个服务拖垮主机。应用处理 SIGTERM:停止接收新请求、排空进行中请求,再退出。depends_on 只控制启动顺序,不等于就绪。
走向生产
单机 Compose 适合预发和小流量生产。需要多主机时,再迁移到托管容器服务或 Kubernetes;在此之前,应把镜像构建、密钥注入、日志和备份做好,避免把 Compose 用成无法扩展的临时方案。
代码示例
# docker-compose.yml
services:
api:
build: ./api
environment:
DATABASE_URL: postgres://app:app@db:5432/app
REDIS_URL: redis://redis:6379
NODE_ENV: production
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 10s
timeout: 3s
retries: 3
start_period: 15s
deploy:
resources:
limits: { cpus: "1.0", memory: 512M }
restart: unless-stopped
stop_grace_period: 30s
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: app
volumes: ["db-data:/var/lib/postgresql/data"]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app"]
interval: 5s
retries: 5
restart: unless-stopped
redis:
image: redis:7
restart: unless-stopped
volumes:
db-data:
// A health endpoint that distinguishes readiness from liveness.
app.get("/health", (req, res) => {
if (shuttingDown) return res.status(503).end(); // draining -> not ready
res.status(200).json({ status: "ok" });
});
app.get("/health/live", (req, res) => res.status(200).json({ status: "alive" }));
let shuttingDown = false;
const server = app.listen(3000);
process.on("SIGTERM", async () => {
shuttingDown = true; // /health starts returning 503; the LB stops sending traffic
server.close(); // stop accepting new connections
await drainInFlight(); // wait for active requests (with a timeout)
await db.close();
process.exit(0);
});
# Install dependencies in a layer that changes only when package.json changes.
COPY package.json package-lock.json ./
RUN npm ci
# Copy the source — this changes on every commit, so it comes after the install.
COPY . .
RUN npm run build
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM gcr.io/distroless/nodejs22 AS runtime
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
CMD ["dist/index.js"]
# Kubernetes: inject the secret as an environment variable at runtime.
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: api-secrets
key: database-url