Files
junhong_cmp_fiber/Dockerfile.api
huang a80dc1e69d
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 3m47s
修复容器健康检查失败的核心问题:IPv6 vs IPv4 和权限
问题诊断(本地运行镜像验证):
1. 服务实际已启动在 3000 端口
2. 从宿主机访问健康检查  成功
3. 容器内部 wget localhost:3000  失败 (Connection refused)
4. 健康检查尝试连接 [::1]:3000 (IPv6),但 Fiber 只监听 IPv4

根本原因:
- wget localhost 优先解析为 IPv6 地址 [::1]
- Fiber 默认监听 0.0.0.0:3000 (仅 IPv4)
- Docker 健康检查失败 → 容器标记 unhealthy → Worker 无法启动

修复内容:
1. Dockerfile.api 健康检查: localhost → 127.0.0.1 (强制 IPv4)
2. docker-compose.prod.yml 健康检查: 同步修改
3. Dockerfile.api: 创建 logs 目录并设置 appuser 权限
4. cmd/api/main.go: OpenAPI 文档路径改为 logs/openapi.yaml
2026-01-20 11:50:28 +08:00

85 lines
2.3 KiB
Docker
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ================================
# 阶段 1: 构建阶段
# ================================
FROM --platform=linux/amd64 registry.boss160.cn/base/golang:1.25.6-alpine AS builder
# 使用阿里云镜像源加速
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 设置工作目录
WORKDIR /build
# 设置 Go 代理(必须在所有 go 命令前)
ENV GOPROXY=https://goproxy.cn,direct \
GO111MODULE=on \
CGO_ENABLED=0
# 安装必要的构建工具
RUN apk add --no-cache git ca-certificates tzdata
# 复制 go.mod 和 go.sum利用 Docker 缓存)
COPY go.mod go.sum ./
RUN go mod download
# 复制源代码
COPY . .
# 编译 API 服务(静态链接,使用并行编译)
RUN GOOS=linux GOARCH=amd64 go build \
-ldflags="-w -s" \
-o /build/api \
./cmd/api
# 下载 golang-migrate 工具(使用 GOPROXY 加速)
RUN go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
# ================================
# 阶段 2: 运行阶段
# ================================
FROM --platform=linux/amd64 registry.boss160.cn/base/alpine:3.19
# 使用阿里云镜像源加速
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 安装运行时依赖
RUN apk add --no-cache ca-certificates tzdata bash
# 设置时区
ENV TZ=Asia/Shanghai
# 创建非 root 用户
RUN addgroup -g 1000 appuser && \
adduser -D -u 1000 -G appuser appuser
# 设置工作目录
WORKDIR /app
# 从构建阶段复制二进制文件
COPY --from=builder /build/api /app/api
COPY --from=builder /go/bin/migrate /usr/local/bin/migrate
# 复制配置文件和迁移文件
COPY configs /app/configs
COPY migrations /app/migrations
# 复制启动脚本
COPY docker/entrypoint-api.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# 创建日志目录并设置权限(在切换用户前)
RUN mkdir -p /app/logs && chown -R appuser:appuser /app/logs
# 切换到非 root 用户
USER appuser
# 暴露端口
EXPOSE 3000
# 健康检查(使用 127.0.0.1 强制 IPv4避免 IPv6 连接问题)
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:3000/health || exit 1
# 启动命令
ENTRYPOINT ["/app/entrypoint.sh"]