如何从 Kubernetes 集群外部连接到 CockroachDB?

How can I connect to CockroachDB from outside the Kubernetes cluster?

我已经设置并部署了一个包含三个 CockroachDB pods、as per docs 的 Kubernetes 有状态集。我最终 objective 是查询数据库而不需要使用 kubectl。我的中级 objective 是查询数据库而不实际进入数据库 pod。

我将一个端口从 pod 转发到我的本地计算机,并尝试连接:

$ kubectl port-forward cockroachdb-0 26257
Forwarding from 127.0.0.1:26257 -> 26257
Forwarding from [::1]:26257 -> 26257

# later, after attempting to connect:
Handling connection for 26257
E0607 16:32:20.047098   80112 portforward.go:329] an error occurred forwarding 26257 -> 26257: error forwarding port 26257 to pod cockroachdb-0_mc-red, uid : exit status 1: 2017/06/07 04:32:19 socat[40115] E connect(5, AF=2 127.0.0.1:26257, 16): Connection refused


$ cockroach node ls --insecure --host localhost --port 26257
Error: unable to connect or connection lost.

Please check the address and credentials such as certificates (if attempting to
communicate with a secure cluster).

rpc error: code = Internal desc = transport is closing
Failed running "node"

有人设法做到这一点吗?

从 Kubernetes 集群内部,您可以通过连接 cockroachdb-public DNS 名称与数据库对话。在 the docs 中,对应于示例命令:

kubectl run cockroachdb -it --image=cockroachdb/cockroach --rm --restart=Never -- sql --insecure --host=cockroachdb-public

虽然该命令正在使用 CockroachDB 映像,但当 运行 Kubernetes 集群时,您使用的任何 Postgres 客户端驱动程序都应该能够连接到 cockroachdb-public

从 Kubernetes 集群外部连接到数据库需要公开 cockroachdb-public 服务。细节在某种程度上取决于你的 Kubernetes 集群是如何部署的,所以我建议你查看他们的文档: https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#exposing-the-service

如果您好奇的话,转发端口 26257 对您不起作用的原因是,只有当 Pod 中的进程正在侦听本地主机时,来自 Pod 的端口转发才有效,但是 CockroachDB 进程在statefulset 配置设置为侦听 pod 的主机名(通过 --host 标志配置)。