K8s Rest API 基礎概念&基本功能 說明 v1.11
阿新 • • 發佈:2018-12-16
K8s 實用 api 速查
首先,需要在K8s叢集獲取一串用於認證的token。這裡省略這個步驟。 以下命令中的所有如下格式的命令,均替換為完整的token才能夠執行。
-H "Authorization: Bearer ey...Xg"
查詢Pods的基本資訊
通過使用k8s-api介面,查詢Pods的基本資訊。返回一個json格式的長檔案。
curl -k -v -X GET -H "Authorization: Bearer ey...Xg" -H "Content-Type: application/json" https://59.110.220.63:6443/api/v1/namespaces/default/pods/
查詢指定Pod的資訊
在上一條命令中的最後,加入指定的Pod名,即可獲得指定Pod的資訊。
curl -k -v -X GET -H "Authorization: Bearer ey..Xg" -H "Content-Type: application/json" https://59.110.220.63:6443/api/v1/namespaces/default/pods/pod-jupyter-233
建立指定的Pod
Pod中的各種資訊由命令中的json所決定
curl -k -v -X POST -H "Authorization: Bearer ey..Xg" -H 'Content-Type: application/json' --data ' { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "pod-jupyter-233", "namespace": "default", "labels": { "name": "jupyter" } }, "spec": { "restartPolicy": "Always", "containers": [ { "name": "pod-jupyter-233", "image": "tensorflow/tensorflow:latest", "imagePullPolicy": "Never", "ports": [ { "containerPort": 8888 } ], "command": [ "/run_jupyter.sh" ], "args": [ "--allow-root", "--NotebookApp.token=abcdef" ], "volumeMounts": [ { "mountPath": "/notebooks", "name": "test-volume" } ] } ], "volumes": [ { "name": "test-volume", "hostPath": { "path": "/mnt/userid", "type": "Directory" } } ] } } ' https://59.110.220.63:6443/api/v1/namespaces/default/pods
建立Pod的相應Service
Service是K8s中,用於自動分配範圍從30000至32767的埠號的一個服務型別。每一個Pod如果想獲取一個公網IP和相應的port,都必須建立一個相應的Service。
【!】注意! 在k8s中,外網訪問Pod的IP地址可以為任意一臺連入叢集的主機IP地址。
curl -k -v -X POST -H "Authorization: Bearer ey..Xg" -H 'Content-Type: application/json' --data ' { "kind": "Service", "apiVersion": "v1", "metadata": { "name": "pod-jupyter-233", "namespace": "default", "labels": { "name": "jupyter" } }, "spec": { "type":"NodePort", "ports": [{ "protocol":"TCP", "port": 8888 }], "selector": {"name": "jupyter"} } } ' https://59.110.220.63:6443/api/v1/namespaces/default/services
查詢全部的Services的資訊
通過查詢Services的資訊,可以獲取K8s分配給Pod的外網埠號等資訊。
curl -k -v -X GET -H "Authorization: Bearer ey..Xg" -H "Content-Type: application/json" https://59.110.220.63:6443/api/v1/namespaces/default/services
指定一個service名稱,查詢指定名稱的service資訊
用於獲取埠號的常用操作
curl -k -v -X GET -H "Authorization: Bearer ey..Xg" -H "Content-Type: application/json" https://59.110.220.63:6443/api/v1/namespaces/default/services/pod-jupyter-233
刪除已建立的Pod
用於刪除已經存在的Pod。請注意,發起這個HTTP請求後,相應的Pod還需要經歷一段時間的Terminating後,才會真正被刪除。
curl -k -v -X DELETE -H "Authorization: Bearer ey..Xg" -H "Content-Type: application/json" https://59.110.220.63:6443/api/v1/namespaces/default/pods/pod-jupyter-233
刪除已建立的service
刪除service與刪除pod的不同之處在於:service可以立刻被刪除。因此,在結束學員實驗時,請先刪除service,再刪除Pod。
curl -k -v -X DELETE -H "Authorization: Bearer ey..Xg" -H "Content-Type: application/json" https://59.110.220.63:6443/api/v1/namespaces/default/services/pod-jupyter-233
以上,即為K8s的常用API操作。感謝您的閱讀。