1. 23 Kubernetes API介绍
查看集群状态
[root@k8s-master1 ~]# kubectl cluster-info
Kubernetes master is running at https://192.168.56.11:6443
KubeDNS is running at https://192.168.56.11:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
直接访问Kubernetes API需要验证,无法直接访问。
[root@k8s-master1 ~]# curl -k https://192.168.56.11:6443
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {
},
"status": "Failure",
"message": "forbidden: User \"system:anonymous\" cannot get path \"/\"",
"reason": "Forbidden",
"details": {
},
"code": 403
}
通过Proxy访问Kubernetes API
使用kubectl proxy可以在Master本地启动一个代理
[root@k8s-master1 ~]# kubectl proxy
Starting to serve on 127.0.0.1:8001
可以通过127.0.0.1:8001与API Server进行交互
[root@k8s-master1 ~]# curl http://127.0.0.1:8001
{
"paths": [
"/api",
"/api/v1",
"/apis",
"/apis/",
"/apis/admissionregistration.k8s.io",
"/apis/admissionregistration.k8s.io/v1beta1",
"/apis/apiextensions.k8s.io",
"/apis/apiextensions.k8s.io/v1beta1",
"/apis/apiregistration.k8s.io",
"/apis/apiregistration.k8s.io/v1",
"/apis/apiregistration.k8s.io/v1beta1",
"/apis/apps",
...(省略其它输出)
可以通过修改监听地址,并关闭过滤,实现在其它地方登录和查看,这样就可以在本地浏览器访问API。切记不要再生产环境将代理地址暴露在外网。
[root@k8s-master1 ~]# kubectl proxy --address=0.0.0.0 --disable-filter=true
W1105 16:18:45.669591 16730 proxy.go:142] Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious
Starting to serve on [::]:8001
1.1.1. 使用Swagger UI进行API交互
Kubernetes支持Swagger UI访问API,需要在API Server开启,如果已经根据本书使用kubeadm部署的集群,可以通过修改Pod的YAML文件,重建Pod来开启
修改API Server的Pod定义文件
在- kube-apiserver下面一行增加--enable-swagger-ui=true
[root@k8s-master1 ~]# vim /etc/kubernetes/manifests/kube-apiserver.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
component: kube-apiserver
tier: control-plane
name: kube-apiserver
namespace: kube-system
spec:
containers:
- command:
- kube-apiserver
- --enable-swagger-ui=true
- --advertise-address=192.168.56.11
- --allow-privileged=true
删除Pod,kubelet会通过该YAML重建Pod
[root@k8s-master1 ~]# kubectl get pod -n kube-system | grep api
kube-apiserver-linux-node1.unixhot.com 1/1 Running 0 55m
[root@k8s-master1 ~]# kubectl delete pod kube-apiserver-linux-node1.unixhot.com -n kube-system
可以看到配置已经生效
[root@k8s-master1 ~]# kubectl describe pod kube-apiserver-linux-node1.unixhot.com -n kube-system
...
Command:
kube-apiserver
--enable-swagger-ui=true
--advertise-address=192.168.99.27
....
部署一个Swagger UI服务查看API
[root@k8s-master1 ~]# kubectl run swagger-ui --image=swaggerapi/swagger-ui:latest
[root@k8s-master1 ~]# kubectl expose deployment swagger-ui --port=8080 --type=NodePort
[root@k8s-master1 ~]# kubectl get service
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.1.0.1 <none> 443/TCP 43d
swagger-ui NodePort 10.1.205.94 <none> 8080:30410/TCP 34s
因为我们部署的Swagger UI和API Server不在一个域名下,所以会有跨域的问题,Chrome浏览器需要提前安装Allow CROS插件解决