# ============================================ # 第一阶段: 构建前端应用 # ============================================ FROM node:22-alpine AS frontend-builder WORKDIR /app/web # 复制前端依赖文件 COPY web/package.json web/yarn.lock ./ # 安装依赖 RUN yarn install --frozen-lockfile # 复制前端源代码 COPY web/ ./ # 构建前端应用 RUN yarn build # ============================================ # 第二阶段: 构建 Go 后端应用 # ============================================ FROM golang:1.25.1-alpine AS backend-builder WORKDIR /app # 安装必要的构建工具 RUN apk add --no-cache git # 配置 Go 代理(使用国内镜像加速) ENV GOPROXY=https://goproxy.cn,https://goproxy.io,https://mirrors.aliyun.com/goproxy/,direct ENV GOSUMDB=off # 复制 Go 依赖文件 COPY go.mod go.sum ./ # 下载依赖 RUN go mod download # 复制后端源代码 COPY . . # 构建 Go 应用 RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o server main.go # ============================================ # 第三阶段: 创建最终运行镜像 # ============================================ FROM alpine:latest WORKDIR /app # 安装运行时依赖 RUN apk --no-cache add ca-certificates tzdata # 设置时区为上海 ENV TZ=Asia/Shanghai # 从后端构建阶段复制可执行文件 COPY --from=backend-builder /app/server ./server # 从前端构建阶段复制构建产物 # 根据 main.go 配置: # - r.NoRoute() 返回 ./web/index.html # - r.Static("/assets", "./web/static") 提供静态资源 COPY --from=frontend-builder /app/web/dist/index.html ./web/index.html COPY --from=frontend-builder /app/web/dist/assets ./web/static # 暴露端口 EXPOSE 8080 # 启动应用 CMD ["./server"]