123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- # 构建阶段(使用Debian基础镜像保证glibc兼容性)
- FROM golang:1.21-bullseye AS builder
- # 配置Go环境
- ENV GOPROXY=https://goproxy.cn,direct \
- CGO_ENABLED=1 \
- GOOS=linux \
- GOARCH=amd64 \
- GO111MODULE=on
- # 配置Debian镜像源和DNS
- RUN echo 'deb https://mirrors.aliyun.com/debian/ bullseye main non-free contrib' > /etc/apt/sources.list && \
- echo 'deb-src https://mirrors.aliyun.com/debian/ bullseye main non-free contrib' >> /etc/apt/sources.list && \
- echo 'nameserver 8.8.8.8' > /etc/resolv.conf && \
- echo 'nameserver 114.114.114.114' >> /etc/resolv.conf
- # 安装构建依赖
- RUN apt-get update && apt-get install -y --no-install-recommends \
- gcc \
- g++ \
- libsqlite3-dev \
- pkg-config \
- ca-certificates \
- && apt-get clean \
- && rm -rf /var/lib/apt/lists/*
- WORKDIR /app
- # 复制依赖清单
- COPY go.mod go.sum ./
- RUN go mod download
- # 复制源代码
- COPY . .
- # 构建优化参数
- RUN go build -v -ldflags="-w -s -linkmode external -extldflags '-static'" \
- -tags "osusergo netgo sqlite_omit_load_extension" \
- -o /app/main cmd/main.go
- # 运行时阶段
- FROM debian:bullseye-slim
- # 设置容器时区
- ENV TZ=Asia/Shanghai
- RUN apt-get update && apt-get install -y \
- ca-certificates \
- tzdata \
- libsqlite3-0 \
- curl \
- && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
- && echo $TZ > /etc/timezone \
- && rm -rf /var/lib/apt/lists/*
- # 创建专用用户(固定uid/gid)
- RUN groupadd -g 10001 appgroup && \
- useradd -u 10001 -g appgroup -d /app -s /sbin/nologin appuser
- # 设置工作目录
- WORKDIR /app
- # 从构建阶段复制文件
- COPY --from=builder --chown=appuser:appgroup /app/main .
- COPY --chown=appuser:appgroup config.yaml .
- COPY --chown=appuser:appgroup --from=builder /app/data/json_files ./data/json_files
- # 初始化容器环境
- RUN mkdir -p /app/data \
- && chown -R appuser:appgroup /app \
- && chmod 755 /app/main \
- && chmod 644 config.yaml \
- && chmod -R 755 /app/data
- # 安全增强配置
- RUN echo "hosts: files dns" > /etc/nsswitch.conf && \
- echo "appuser hard nofile 65535" >> /etc/security/limits.conf && \
- echo "appuser soft nofile 65535" >> /etc/security/limits.conf
- # 健康检查(使用curl代替wget)
- HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
- CMD curl -fsS http://localhost:8080/healthz || exit 1
- # 运行时配置
- USER appuser
- EXPOSE 8080
- ENTRYPOINT ["./main"]
- CMD ["--config", "config.yaml", "server"]
|