feat(docker): 优化Docker构建流程并支持生产环境部署

- 引入多阶段构建,分离构建与运行时环境
- 使用node:20-alpine作为构建基础镜像,减小体积
- 添加pnpm包管理器并优化依赖安装流程
- 利用缓存机制提升构建效率
- 新增nginx.conf配置文件解决Vue Router历史模式404问题
- 设置静态资源缓存策略提升性能
- 更改默认启动命令为Nginx服务方式运行应用
- 移除开发服务器相关指令,适配生产部署需求
This commit is contained in:
coolxitech
2025-12-13 10:19:58 +08:00
parent 8637e50115
commit 469c5a0170
2 changed files with 43 additions and 10 deletions

View File

@@ -1,17 +1,33 @@
FROM node:latest
RUN mkdir -p /workspace
WORKDIR /workspace
# ========= 阶段1构建 =========
FROM node:20-alpine AS builder
# 使用国内镜像加速(可选)
RUN npm config set registry https://registry.npmmirror.com
RUN cd /workspace
WORKDIR /app
RUN git clone https://github.com/setube/ogame-vue-ts.git
# 先复制依赖文件,利用缓存
COPY package.json pnpm-lock.yaml* ./
RUN mv ./ogame-vue-ts/* . ; rm -rf ./ogame-vue-ts/
# 安装 pnpm 并安装依赖
RUN corepack enable && corepack prepare pnpm@latest --activate \
&& pnpm install --frozen-lockfile
RUN npm install -g pnpm ; pnpm install ; npx vite build
# 复制源码
COPY . .
CMD ["npx", "vite", "preview", "--host", "0.0.0.0", "--port", "25121"]
# 生产构建
RUN pnpm run build
# ========= 阶段2运行时 =========
FROM nginx:alpine
# 复制构建产物
COPY --from=builder /app/dist /usr/share/nginx/html
# 解决 Vue Router history 模式 404 问题
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

17
nginx.conf Normal file
View File

@@ -0,0 +1,17 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
}
# 可选:缓存静态资源
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot) {
expires 1y;
add_header Cache-Control "public, immutable";
}
}