Dockerfile 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # 构建阶段(使用Debian基础镜像保证glibc兼容性)
  2. FROM golang:1.21-bullseye AS builder
  3. # 配置Go环境
  4. ENV GOPROXY=https://goproxy.cn,direct \
  5. CGO_ENABLED=1 \
  6. GOOS=linux \
  7. GOARCH=amd64 \
  8. GO111MODULE=on
  9. # 配置Debian镜像源和DNS
  10. RUN echo 'deb https://mirrors.aliyun.com/debian/ bullseye main non-free contrib' > /etc/apt/sources.list && \
  11. echo 'deb-src https://mirrors.aliyun.com/debian/ bullseye main non-free contrib' >> /etc/apt/sources.list && \
  12. echo 'nameserver 8.8.8.8' > /etc/resolv.conf && \
  13. echo 'nameserver 114.114.114.114' >> /etc/resolv.conf
  14. # 安装构建依赖
  15. RUN apt-get update && apt-get install -y --no-install-recommends \
  16. gcc \
  17. g++ \
  18. libsqlite3-dev \
  19. pkg-config \
  20. ca-certificates \
  21. && apt-get clean \
  22. && rm -rf /var/lib/apt/lists/*
  23. WORKDIR /app
  24. # 复制依赖清单
  25. COPY go.mod go.sum ./
  26. RUN go mod download
  27. # 复制源代码
  28. COPY . .
  29. # 构建优化参数
  30. RUN go build -v -ldflags="-w -s -linkmode external -extldflags '-static'" \
  31. -tags "osusergo netgo sqlite_omit_load_extension" \
  32. -o /app/main cmd/main.go
  33. # 运行时阶段
  34. FROM debian:bullseye-slim
  35. # 设置容器时区
  36. ENV TZ=Asia/Shanghai
  37. RUN apt-get update && apt-get install -y \
  38. ca-certificates \
  39. tzdata \
  40. libsqlite3-0 \
  41. curl \
  42. && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
  43. && echo $TZ > /etc/timezone \
  44. && rm -rf /var/lib/apt/lists/*
  45. # 创建专用用户(固定uid/gid)
  46. RUN groupadd -g 10001 appgroup && \
  47. useradd -u 10001 -g appgroup -d /app -s /sbin/nologin appuser
  48. # 设置工作目录
  49. WORKDIR /app
  50. # 从构建阶段复制文件
  51. COPY --from=builder --chown=appuser:appgroup /app/main .
  52. COPY --chown=appuser:appgroup config.yaml .
  53. COPY --chown=appuser:appgroup --from=builder /app/data/json_files ./data/json_files
  54. # 初始化容器环境
  55. RUN mkdir -p /app/data \
  56. && chown -R appuser:appgroup /app \
  57. && chmod 755 /app/main \
  58. && chmod 644 config.yaml \
  59. && chmod -R 755 /app/data
  60. # 安全增强配置
  61. RUN echo "hosts: files dns" > /etc/nsswitch.conf && \
  62. echo "appuser hard nofile 65535" >> /etc/security/limits.conf && \
  63. echo "appuser soft nofile 65535" >> /etc/security/limits.conf
  64. # 健康检查(使用curl代替wget)
  65. HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
  66. CMD curl -fsS http://localhost:8080/healthz || exit 1
  67. # 运行时配置
  68. USER appuser
  69. EXPOSE 8080
  70. ENTRYPOINT ["./main"]
  71. CMD ["--config", "config.yaml", "server"]