- 使用阿里云镜像源替换默认的 golang:1.23-alpine - 配置 Alpine 包管理器使用阿里云镜像源 - 设置 Go 模块代理为国内 goproxy.cn - 解决 i/o timeout 连接问题
71 lines
1.8 KiB
Docker
71 lines
1.8 KiB
Docker
# Photography Portfolio Backend Dockerfile
|
|
# 多阶段构建,优化镜像大小和安全性
|
|
|
|
# Stage 1: 构建阶段
|
|
FROM registry.cn-hangzhou.aliyuncs.com/library/golang:1.23-alpine AS builder
|
|
|
|
# 设置工作目录
|
|
WORKDIR /app
|
|
|
|
# 配置镜像源加速
|
|
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
|
|
|
# 安装构建依赖
|
|
RUN apk add --no-cache git ca-certificates tzdata
|
|
|
|
# 配置 Go 模块代理
|
|
ENV GOPROXY=https://goproxy.cn,direct
|
|
ENV GOSUMDB=sum.golang.google.cn
|
|
|
|
# 复制 go mod 文件并下载依赖
|
|
COPY go.mod go.sum ./
|
|
RUN go mod download
|
|
|
|
# 复制源代码
|
|
COPY . .
|
|
|
|
# 构建应用程序
|
|
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
|
|
-ldflags='-w -s -extldflags "-static"' \
|
|
-a -installsuffix cgo \
|
|
-o photography-api \
|
|
./cmd/api/main.go
|
|
|
|
# 构建迁移工具
|
|
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
|
|
-ldflags='-w -s -extldflags "-static"' \
|
|
-a -installsuffix cgo \
|
|
-o migrate \
|
|
./cmd/migrate/main.go
|
|
|
|
# Stage 2: 运行阶段
|
|
FROM scratch
|
|
|
|
# 从builder阶段复制时区数据和CA证书
|
|
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
|
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
|
|
|
# 复制编译好的二进制文件
|
|
COPY --from=builder /app/photography-api /photography-api
|
|
COPY --from=builder /app/migrate /migrate
|
|
|
|
# 复制配置文件和脚本
|
|
COPY --from=builder /app/configs /configs
|
|
COPY --from=builder /app/scripts /scripts
|
|
COPY --from=builder /app/pkg/migration/migrations /pkg/migration/migrations
|
|
|
|
# 设置时区
|
|
ENV TZ=Asia/Shanghai
|
|
|
|
# 创建非root用户 (在scratch镜像中需要手动创建)
|
|
USER 65534:65534
|
|
|
|
# 暴露端口
|
|
EXPOSE 8080
|
|
|
|
# 健康检查
|
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
|
CMD ["/photography-api", "--health-check"]
|
|
|
|
# 启动应用
|
|
ENTRYPOINT ["/photography-api"] |