ccccccc / Dockerfile
cnmksjs's picture
Upload 49 files
24fd742 verified
# 多阶段构建 - 完整聊天应用Dockerfile
# 这个Dockerfile将前端和后端打包到一个容器中(可选方案)
# 阶段1: 构建前端
FROM node:18-alpine as frontend-build
WORKDIR /app/client
# 复制前端package.json
COPY client/package*.json ./
# 安装前端依赖
RUN npm ci
# 复制前端源代码
COPY client/ ./
# 构建前端
RUN npm run build
# 阶段2: 构建后端
FROM node:18-alpine as backend-build
WORKDIR /app/server
# 复制后端package.json
COPY server/package*.json ./
# 安装后端依赖
RUN npm ci --only=production
# 复制后端源代码
COPY server/ ./
# 阶段3: 生产环境
FROM node:18-alpine
# 安装必要的系统依赖
RUN apk add --no-cache \
nginx \
wget \
curl \
supervisor \
&& rm -rf /var/cache/apk/*
# 创建应用用户
RUN addgroup -g 1001 -S appuser && \
adduser -S appuser -u 1001
# 设置工作目录
WORKDIR /app
# 复制后端文件
COPY --from=backend-build --chown=appuser:appuser /app/server ./server
# 复制前端构建文件
COPY --from=frontend-build --chown=appuser:appuser /app/client/dist ./client/dist
# 创建nginx配置
RUN mkdir -p /etc/nginx/conf.d
COPY --chown=appuser:appuser client/nginx.conf /etc/nginx/conf.d/default.conf
# 创建supervisor配置
RUN mkdir -p /etc/supervisor/conf.d
COPY --chown=appuser:appuser <<EOF /etc/supervisor/conf.d/supervisord.conf
[supervisord]
nodaemon=true
user=root
logfile=/var/log/supervisor/supervisord.log
pidfile=/var/run/supervisord.pid
[program:nginx]
command=nginx -g "daemon off;"
autostart=true
autorestart=true
stderr_logfile=/var/log/nginx/error.log
stdout_logfile=/var/log/nginx/access.log
user=appuser
[program:node]
command=node server/index.js
directory=/app
autostart=true
autorestart=true
stderr_logfile=/var/log/node/error.log
stdout_logfile=/var/log/node/access.log
user=appuser
environment=NODE_ENV=production
EOF
# 创建日志目录
RUN mkdir -p /var/log/nginx /var/log/node /var/log/supervisor && \
chown -R appuser:appuser /var/log/nginx /var/log/node /var/log/supervisor
# 修改nginx配置以适应单容器部署
RUN sed -i 's/proxy_pass http:\/\/localhost:5000/proxy_pass http:\/\/127.0.0.1:5000/g' /etc/nginx/conf.d/default.conf
# 暴露端口
EXPOSE 80 5000
# 环境变量
ENV NODE_ENV=production
ENV PORT=5000
ENV MONGODB_URI=mongodb://mongo:27017/chatapp
# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:80 && \
wget --no-verbose --tries=1 --spider http://localhost:5000/api/health || exit 1
# 切换到应用用户
USER appuser
# 启动supervisor
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]