Files
Edu/services/api-gateway/Dockerfile

55 lines
1.9 KiB
Docker
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 多阶段构建api-gateway 生产镜像
# 用法docker build -t edu/api-gateway:latest -f services/api-gateway/Dockerfile .
# 构建上下文必须是仓库根目录(需访问 packages/shared-go 与 go.work
# ============ Builder ============
FROM golang:1.25-alpine AS builder
WORKDIR /app
# 使用国内 Go 模块代理(容器内无法访问 proxy.golang.org
ENV GOPROXY=https://goproxy.cn,direct
ENV GOSUMDB=off
# git 与 ca-certificates 为 go mod 下载所需
RUN apk add --no-cache git ca-certificates
# 利用 go.work 时需拷贝根 go.work 与 shared-go 包
# 注意go.work 引用了 push-gateway但本构建仅需要 api-gateway + shared-go
# 故生成精简版 go.work 避免加载缺失模块
COPY go.work.sum ./
COPY packages/shared-go ./packages/shared-go
COPY services/api-gateway/go.mod services/api-gateway/go.sum ./services/api-gateway/
# 生成仅含 api-gateway + shared-go 的精简 go.work
RUN printf 'go 1.25.0\n\nuse (\n ./packages/shared-go\n ./services/api-gateway\n)\n' > go.work
RUN cd services/api-gateway && go mod download
# 拷源码并构建
COPY services/api-gateway ./services/api-gateway
COPY packages/shared-go ./packages/shared-go
# 静态编译CGO_DISABLED 便于 alpine 运行
# 注入 version 便于可观测性资源属性
RUN CGO_ENABLED=0 GOOS=linux go build \
-ldflags="-s -w -X main.version=docker" \
-o /app/bin/api-gateway \
./services/api-gateway
# ============ Runtime ============
FROM alpine:3.20 AS runner
WORKDIR /app
RUN apk add --no-cache ca-certificates tzdata wget
# 非 root 用户
RUN addgroup -g 1001 -S app && adduser -S app -u 1001 -G app
COPY --from=builder /app/bin/api-gateway /app/api-gateway
USER app
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget --quiet --spider http://localhost:8080/healthz || exit 1
ENTRYPOINT ["/app/api-gateway"]