Files
tyapi-server/Dockerfile
2025-07-28 01:46:39 +08:00

68 lines
1.5 KiB
Docker

# 第一阶段:构建阶段
FROM golang:1.23.4-alpine AS builder
# 设置工作目录
WORKDIR /app
# 安装必要的包
RUN apk add --no-cache git ca-certificates tzdata
# 复制模块文件
COPY go.mod go.sum ./
# 下载依赖
RUN go mod download
# 复制源代码
COPY . .
# 构建应用程序
ARG VERSION=1.0.0
ARG COMMIT=dev
ARG BUILD_TIME
RUN BUILD_TIME=${BUILD_TIME:-$(date -u +"%Y-%m-%dT%H:%M:%SZ")} && \
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
-ldflags "-X main.version=${VERSION} -X main.commit=${COMMIT} -X main.date=${BUILD_TIME} -w -s" \
-a -installsuffix cgo \
-o tyapi-server \
cmd/api/main.go
# 第二阶段:运行阶段
FROM alpine:3.19
# 安装必要的包
RUN apk --no-cache add ca-certificates tzdata curl && \
update-ca-certificates
# 设置时区
ENV TZ=Asia/Shanghai
# 创建非root用户
RUN addgroup -g 1001 tyapi && \
adduser -D -s /bin/sh -u 1001 -G tyapi tyapi
# 设置工作目录
WORKDIR /app
# 从构建阶段复制二进制文件
COPY --from=builder /app/tyapi-server .
# 复制配置文件
COPY --chown=tyapi:tyapi config.yaml .
COPY --chown=tyapi:tyapi configs/ ./configs/
# 创建日志目录
RUN mkdir -p logs && chown -R tyapi:tyapi logs
# 切换到非root用户
USER tyapi
# 暴露端口
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# 启动命令
CMD ["./tyapi-server", "-env=production"]