Dockerfile 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # 第一阶段:构建阶段,使用官方 Golang 镜像编译程序
  2. FROM golang:1.23-alpine AS builder
  3. # 安装必要的构建工具(git 用于获取 GitHub 依赖,ca-certificates 用于 HTTPS 连接)
  4. RUN apk add --no-cache git ca-certificates
  5. # 设置工作目录
  6. WORKDIR /app
  7. # 设置 Go 环境变量
  8. ENV CGO_ENABLED=0 \
  9. GOOS=linux \
  10. GOARCH=amd64 \
  11. GOPROXY=https://goproxy.cn,direct
  12. # 复制 go.mod 和 go.sum 文件
  13. COPY go.mod go.sum ./
  14. # 下载依赖
  15. RUN go mod download
  16. # 复制源代码
  17. COPY . .
  18. # 编译应用程序
  19. RUN go build -ldflags="-w -s" -o city_chips ./cmd/server
  20. # 第二阶段:运行阶段,使用极简的 alpine 镜像
  21. FROM alpine:latest
  22. # 安装必要的运行时依赖
  23. RUN apk --no-cache add ca-certificates tzdata && \
  24. addgroup -g 1001 -S appgroup && \
  25. adduser -u 1001 -S appuser -G appgroup
  26. # 设置时区
  27. ENV TZ=Asia/Shanghai
  28. # 设置工作目录
  29. WORKDIR /app
  30. # 从构建阶段复制二进制文件
  31. COPY --from=builder /app/city_chips ./
  32. # 复制配置文件和模板文件
  33. COPY --from=builder /app/config ./config
  34. COPY --from=builder /app/templates ./templates
  35. # 创建日志目录
  36. RUN mkdir -p storage/logs && \
  37. chown -R appuser:appgroup /app
  38. # 切换到非 root 用户
  39. USER appuser
  40. # 暴露应用端口(根据配置文件,默认是 8000)
  41. EXPOSE 8000
  42. # 运行应用程序
  43. CMD ["./city_chips"]