client go远程连接k8s(minikube)

复制配置文件到本地

  1. 先将minikube拷贝到本地(或者只拷贝.kube\config需要的文件)
1
cp -r /home/docker_user/.minikube /root/
  1. 拷贝.kube文件夹
1
cp -r /home/docker_user/.kube /root/

添加ssh端口转发

本地肯定是访问不了的,所以需要在本地试验环境添加远程主机的端口转发。

windows端口转发,打开windows的cmd,输入命令:

1
2
3
4
5
# 表示在本地启动18443端口,与远程主机root@192.168.56.101建议连接,端口转发到远程主机192.168.49.2:8443上去, 执行完窗口会hold住
# 192.168.49.2是k8s节点ip, 使用`minikube node list`查看

C:\Users\a94391> ssh -L 18443:192.168.49.2:8443 -N -f docker_user@192.168.56.101
docker_user@192.168.56.101's password:

此时可以在本地开发环境通过curl进行简单验证:

curl https://127.0.0.1:18443
只要不是 Connection refused 那么可以认为连接成功了。

修改config内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
apiVersion: v1
clusters:
- cluster:
# 这里修改ca证书位置
certificate-authority: C:/Users/94391/.minikube/ca.crt
extensions:
- extension:
last-update: Sat, 26 Nov 2022 17:40:15 CST
provider: minikube.sigs.k8s.io
version: v1.28.0
name: cluster_info
# 这里修改成转发地址
server: https://127.0.0.1:18443
name: minikube
contexts:
- context:
cluster: minikube
extensions:
- extension:
last-update: Sat, 26 Nov 2022 17:40:15 CST
provider: minikube.sigs.k8s.io
version: v1.28.0
name: context_info
namespace: default
user: minikube
name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
user:
# 这里修改客户端证书位置
client-certificate: C:/Users/94391/.minikube/profiles/minikube/client.crt
client-key: C:/Users/94391/.minikube/profiles/minikube/client.key

代码测试

client go对应k8s-1.23.3版本

1
go get k8s.io/client-go@v0.23.3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// config, 默认位置 $HOME/.kube/config
// masterUrl为空, 就会使用config配置作为连接配置
config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
if err != nil {
panic(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
coreV1 := clientset.CoreV1()
pod, err := coreV1.Pods("kube-system").Get(context.TODO(), "etcd-minikube", v1.GetOptions{})
if err != nil {
fmt.Println(err)
} else {
fmt.Println(pod.Name)
}