Skip to content

Node.js Docker 部署

推荐 Dockerfile

dockerfile
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force

FROM node:22-alpine
WORKDIR /app
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -G nodejs
COPY --from=builder /app/node_modules ./node_modules
COPY . .
USER nodejs
EXPOSE 3000
CMD ["node", "app.js"]

关键优化点

优化说明
alpine基础镜像仅 ~150MB(非 alpine 约 1GB)
多阶段构建构建与运行分离,最终镜像不含 devDeps
npm cinpm install 快且确定性安装
非 root 用户安全最佳实践
.dockerignore排除 node_modules、日志、.env

.dockerignore

node_modules
npm-debug.log
.env
.git
dist
*.md

Docker Compose

yaml
version: '3.8'
services:
  app:
    build: .
    ports: ['3000:3000']
    env_file: .env
    depends_on: [redis, mysql]

  redis:
    image: redis:7-alpine
    ports: ['6379:6379']

  mysql:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: 123456
      MYSQL_DATABASE: myapp
    ports: ['3306:3306']
    volumes: ['./data/mysql:/var/lib/mysql']

PM2 生产部署

bash
npm install -g pm2

pm2 start app.js --name my-app -i max
pm2 save                # 保存当前进程列表
pm2 startup             # 设置开机自启

# 更新部署(零停机)
git pull && npm ci && pm2 reload my-app

部署流水线(简易版)

bash
# 1. 构建
docker build -t my-app:latest .

# 2. 导出/推送
docker save my-app:latest | gzip > my-app.tar.gz
# 或 docker push registry.example.com/my-app:latest

# 3. 服务器拉取运行
docker load < my-app.tar.gz
docker compose up -d

# 4. 健康检查
curl http://localhost:3000/health