ask-docker-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<critical_constraints> ❌ NO running as root → use
USER node
or create user ❌ NO unpinned base images →
node:18-alpine3.18
❌ NO hardcoded secrets → use .env files ✅ MUST use multi-stage builds for compiled/Node.js apps ✅ MUST use .dockerignore (exclude node_modules, .git) </critical_constraints>
<multi_stage_template>
dockerfile
undefined
<critical_constraints> ❌ 禁止以root用户运行 → 使用
USER node
或创建专用用户 ❌ 禁止使用未固定版本的基础镜像 → 例如
node:18-alpine3.18
❌ 禁止硬编码密钥 → 使用.env文件 ✅ 编译型/Node.js应用必须使用多阶段构建 ✅ 必须使用.dockerignore(排除node_modules、.git) </critical_constraints>
<multi_stage_template>
dockerfile
undefined

Build Stage

Build Stage

FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build
FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build

Production Stage

Production Stage

FROM node:18-alpine WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/package.json ./ RUN npm install --production USER node CMD ["npm", "start"]
</multi_stage_template>

<layer_caching>
Order: least → most frequently changed
1. Copy package.json, install deps
2. THEN copy source code
</layer_caching>

<compose>
- Use healthcheck for dependencies
- Use .env for secrets
- Version 3.8 if required
</compose>

<debugging>
- Connectivity: `docker compose exec app curl db:5432`
- Logs: `docker logs -f <container_id>`
- Shell: `docker exec -it <container_id> /bin/sh`
</debugging>
FROM node:18-alpine WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/package.json ./ RUN npm install --production USER node CMD ["npm", "start"]
</multi_stage_template>

<layer_caching>
顺序:从变更频率最低到最高
1. 复制package.json,安装依赖
2. 然后复制源代码
</layer_caching>

<compose>
- 为依赖服务配置健康检查
- 使用.env管理密钥
- 如需特定版本,使用3.8版本
</compose>

<debugging>
- 连通性检测:`docker compose exec app curl db:5432`
- 日志查看:`docker logs -f <container_id>`
- 进入容器shell:`docker exec -it <container_id> /bin/sh`
</debugging>