Golang 发送 Https 请求报错 `x509 certificate signed by unknown authority` (在 Docker 中运行)

请求报错如下

1
2
3
4
5
6
7
panic: Post "https://oapi.dingtalk.com/robot/send?access_token=xxx": x509: certificate signed by unknown authority

goroutine 1 [running]:
main.sendDing(0xc000104140, 0x32, 0xc0001041c0, 0x40, 0xc0000a8870, 0x7, 0xc0000aa580, 0x14, 0xc0001c0080, 0x7e)
/build/main.go:161 +0x921
main.main()
/build/main.go:222 +0x535

原因分析

由于使用了 scratch 做基础包, 里面没有和 https 相关的证书.

1
2
3
4
FROM scratch
WORKDIR /project
COPY --from=builder /build/main /project/main
ENTRYPOINT [ "/project/main" ]

解决方法

手动下载证书 ca-bundle.crt, 重命名为 ca-certificates.crt 后添加到 Image 镜像中:

1
COPY ./ca-certificates.crt /etc/ssl/certs/

如果连接失效, google ca-certificates.crt download 查找相应信息.

参考: X509: Certificate Signed by Unknown Authority (Running a Go App Inside a Docker Container)

Donate - Support to make this site better.
捐助 - 支持我让我做得更好.