docker容器中go访问https出错tls: failed to verify certificate: x509: certificate signed by unknown authority
docker容器中访问https,是缺少了CA证书,在制作镜像时要记得添加一下证书。
·
引言
最近遇到了一个问题,代码本地跑都没啥问题,但是放到 docker 容器中跑就出错 tls: failed to verify certificate: x509: certificate signed by unknown authority。
就很烦,最终发现是 CA 证书的问题,在此做个记录。
解决方式
2 种方式:
- 在
docker镜像中安装ca-certificates包并更新证书
# 安装CA证书
RUN apt-get update && apt-get install -y ca-certificates
# 更新CA证书(通常安装包时会自动更新,可显式执行确保)
RUN update-ca-certificates
go中处理,我直接跳过证书验证,设置TLSClientConfig InsecureSkipVerify: true,不推荐
var client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
client.Get("https://www.aliyun.com")
code show
简单的写了一个小 demo,可以自行修改 dockerfile 或 main.go 进行验证。
文件结构
- dockerfile
- go.mod
- main.go
dockerfile
FROM golang:1.24-bookworm
WORKDIR "/app"
COPY . .
RUN go mod tidy && go build -o test
FROM debian:bookworm-slim
WORKDIR "/app"
# RUN echo "deb http://mirrors.aliyun.com/debian/ bookworm main non-free contrib\
# deb http://mirrors.aliyun.com/debian-security bookworm/updates main\
# deb http://mirrors.aliyun.com/debian/ bookworm-updates main non-free contrib\
# deb http://mirrors.aliyun.com/debian/ bookworm-backports main non-free contrib\
# deb-src http://mirrors.aliyun.com/debian-security bookworm/updates main\
# deb-src http://mirrors.aliyun.com/debian/ bookworm main non-free contrib\
# deb-src http://mirrors.aliyun.com/debian/ bookworm-updates main non-free contrib\
# deb-src http://mirrors.aliyun.com/debian/ bookworm-backports main non-free contrib\
# " > /etc/apt/sources.list
# RUN apt-get update && apt-get install -y ca-certificates
# RUN update-ca-certificates
COPY --from=0 /app/test .
ENTRYPOINT ["/app/test"]
go.mod
module test
go 1.24.1
main.go
package main
import (
"crypto/tls"
"fmt"
"net/http"
"os"
"time"
)
// 请求遇到这个问题 tls: failed to verify certificate: x509: certificate signed by unknown authority
func main() {
var client = &http.Client{
Timeout: time.Second * 5,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: false,
},
},
}
res, err := client.Get("https://www.aliyun.com")
if err != nil {
fmt.Println(err)
return
}
res.Write(os.Stdout)
}
运行:
docker build -t test .
docker run test
总结
docker 容器中访问 https 请求报错:tls: failed to verify certificate: x509: certificate signed by unknown authority,是缺少了 CA 证书,在制作镜像时要记得添加一下证书。
更多推荐




所有评论(0)