# 构建阶段 FROM golang:1.21-alpine AS builder # 设置工作目录 WORKDIR /app # 安装依赖 RUN apk add --no-cache git ca-certificates tzdata # 复制go mod文件 COPY go.mod go.sum ./ # 下载依赖 RUN go mod download # 复制源代码 COPY . . # 设置构建参数 ARG BUILD_TIME ARG GIT_COMMIT # 构建应用 RUN CGO_ENABLED=0 GOOS=linux go build \ -ldflags="-w -s -X main.buildTime=${BUILD_TIME} -X main.gitCommit=${GIT_COMMIT}" \ -o main . # 运行阶段 FROM alpine:latest # 安装ca证书 RUN apk --no-cache add ca-certificates tzdata WORKDIR /root/ # 从builder阶段复制二进制文件 COPY --from=builder /app/main . # 复制配置文件(可选) COPY --from=builder /app/.env . # 创建非root用户 RUN adduser -D -s /bin/sh appuser USER appuser # 暴露端口 EXPOSE 8080 # 健康检查 HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1 # 运行应用 CMD ["./main"]