寫在最前:本章介紹的是kubectl一些工作中常見基本指令整理,更多請檢視kubernetes官方文檔,或者檢視kubernetes的幫助文檔。通篇下來比較長,建議收藏以便後續查閱。
PS:請勿拿生産環境做測試。
基礎指令:create,delete,get,run,expose,set,explain,edit。
使用以下文法 kubectl 從終端視窗運作指令:
kubectl [command] [TYPE] [NAME] [flags]
其中command TYPE NAME和flags
分别是:
- command:指定要對一個或多個資源執行的操作,例如 create、get、describe、delete。
- TYPE:指定資源類型。資源類型不區分大小寫, 可以指定單數、複數或縮寫形式。例如,以下指令輸出相同的結果:
1、create指令:根據檔案或者輸入來建立資源
# 建立Deployment和Service資源
kubectl create -f test-deployment.yaml
kubectl create -f test-service.yaml
2、kubectl get 列出一個或多個資源。
## 檢視所有的資源資訊
root@k8s-master:~# kubectl get all
NAME READY STATUS RESTARTS AGE
pod/net-test1 1/1 Running 0 4h44m
pod/net-test2 1/1 Running 0 4h44m
pod/net-test3 1/1 Running 0 4h44m
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 5h2m
# 以純文字輸出格式列出所有 pod。
kubectl get pods
# 以純文字輸出格式列出所有 pod,并包含附加資訊(如在節點IP)。
root@k8s-master:~# kubectl get pods -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
net-test1 1/1 Running 0 4h49m 10.200.228.129 172.31.7.111 <none> <none>
net-test2 1/1 Running 0 4h49m 10.200.35.129 172.31.7.112 <none> <none>
net-test3 1/1 Running 0 4h49m 10.200.228.130 172.31.7.111 <none> <none>
# 顯示pod節點的标簽資訊
kubectl get pod --show-labels
# 根據指定标簽比對到具體的pod
kubectl get pods -l app=exampl
# 檢視node節點清單
kubectl get node
# 顯示node節點的标簽資訊
kubectl get node --show-labels
# 檢視服務的詳細資訊,顯示了服務名稱,類型,叢集ip,端口,時間等資訊
root@k8s-master:~# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 5h9m
檢視命名空間
kubectl get ns
# 檢視所有pod所屬的命名空間
kubectl get pod --all-namespaces
# 檢視所有pod所屬的命名空間并且檢視都在哪些節點上運作
kubectl get pod --all-namespaces -o wide
# 檢視目前所有的replica set,顯示了所有的pod的副本數,以及他們的可用數量以及狀态等資訊
root@k8s-master:~# kubectl get rs --all-namespaces
NAMESPACE NAME DESIRED CURRENT READY AGE
kube-system calico-kube-controllers-754966f84c 1 1 1 5h6m
kube-system coredns-79688b6cb4 1 1 1 117m
kubernetes-dashboard dashboard-metrics-scraper-799d786dbf 1 1 1 46m
kubernetes-dashboard dashboard-metrics-scraper-c766885cc 0 0 0 50m
kubernetes-dashboard kubernetes-dashboard-5cf689bbcc 0 0 0 50m
kubernetes-dashboard kubernetes-dashboard-fb8648fd9 1 1 1 46m
#檢視所有deployment
root@k8s-master:~# kubectl get deployment -A
NAMESPACE NAME READY UP-TO-DATE AVAILABLE AGE
kube-system calico-kube-controllers 1/1 1 1 5h7m
kube-system coredns 1/1 1 1 118m
kubernetes-dashboard dashboard-metrics-scraper 1/1 1 1 52m
kubernetes-dashboard kubernetes-dashboard 1/1 1 1 52m
# 檢視已經部署了的所有應用,可以看到容器,以及容器所用的鏡像,标簽等資訊
root@k8s-master:~# kubectl get deploy -o wide -A
NAMESPACE NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR
kube-system calico-kube-controllers 1/1 1 1 5h10m calico-kube-controllers docker.io/calico/kube-controllers:v3.19.3 k8s-app=calico-kube-controllers
kube-system coredns 1/1 1 1 120m coredns harbor.host.com/base/coredns:1.8.7 k8s-app=kube-dns
kubernetes-dashboard dashboard-metrics-scraper 1/1 1 1 54m dashboard-metrics-scraper kubernetesui/metrics-scraper:v1.0.7 k8s-app=dashboard-metrics-scraper
kubernetes-dashboard kubernetes-dashboard 1/1 1 1 54m kubernetes-dashboard kubernetesui/dashboard:v2.5.1 k8s-app=kubernetes-dashboard
3、explain指令:用于顯示資源文檔資訊
root@k8s-master:~# kubectl explain ds
KIND: DaemonSet
VERSION: apps/v1
DESCRIPTION:
DaemonSet represents the configuration of a daemon set.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an
object. Servers should convert recognized schemas to the latest internal
value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
kind <string>
Kind is a string value representing the REST resource this object
represents. Servers may infer this from the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
metadata <Object>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
spec <Object>
The desired behavior of this daemon set. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
status <Object>
The current status of this daemon set. This data may be out of date by some
window of time. Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
4、edit指令:用于編輯資源資訊
使用指令行工具擷取的任何資源都可以使用edit指令編輯。edit指令會打開使用KUBE_EDITOR,GIT_EDITOR 或者EDITOR環境變量定義的編輯器,可以同時編輯多個資源,但所編輯過的資源隻會一次性送出。edit除指令參數外還接受檔案名形式。
# 編輯Deployment nginx的一些資訊
kubectl edit deployment nginx
# 編輯service類型的nginx的一些資訊
kubectl edit service/nginx
5、設定指令:label、completion
label指令:用于更新(增加、修改或删除)資源上的 label(标簽)
- label 必須以字母或數字開頭,可以使用字母、數字、連字元、點和下劃線,最長63個字元。
- 如果--overwrite 為 true,則可以覆寫已有的 label,否則嘗試覆寫 label 将會報錯。
- 如果指定了--resource-version,則更新将使用此資源版本,否則将使用現有的資源版本。
文法label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
# 給名為foo的Pod添加label unhealthy=true
kubectl label pods foo unhealthy=true
# 給名為foo的Pod修改label 為 'status' / value 'unhealthy',且覆寫現有的value
kubectl label --overwrite pods foo status=unhealthy
# 給 namespace 中的所有 pod 添加 label
kubectl label pods --all status=unhealthy
# 僅當resource-version=1時才更新 名為foo的Pod上的label
kubectl label pods foo status=unhealthy --resource-version=1
# 删除名為“bar”的label 。(使用“ - ”減号相連)
kubectl label pods foo bar-
completion指令:用于設定kubectl指令自動補全
$ source <(kubectl completion bash) # setup autocomplete in bash, bash-completion package should be installed first.
$ source <(kubectl completion zsh) # setup autocomplete in zsh
6、kubectl 部署指令:rollout、rolling-update、scale、autoscale
rollout指令:用于對資源進行管理
可用資源包括:deployments,daemonsets。
子指令:
- history(檢視曆史版本)
- pause(暫停資源)
- resume(恢複暫停資源)
- status(檢視資源狀态)
- undo(復原版本)
# 文法
kubectl rollout SUBCOMMAND
# 復原到之前的deployment
kubectl rollout undo deployment/abc
# 檢視daemonet的狀态
kubectl rollout status daemonset/foo
rolling-update指令:執行指定ReplicationController的滾動更新。
該指令建立了一個新的RC, 然後一次更新一個pod方式逐漸使用新的PodTemplate,最終實作Pod滾動更新,new-controller.json需要與之前RC在相同的namespace下。
# 文法
rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC)
# 使用frontend-v2.json中的新RC資料更新frontend-v1的pod
kubectl rolling-update frontend-v1 -f frontend-v2.json
# 使用JSON資料更新frontend-v1的pod
cat frontend-v2.json | kubectl rolling-update frontend-v1 -f -
# 其他的一些滾動更新
kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2
kubectl rolling-update frontend --image=image:v2
kubectl rolling-update frontend-v1 frontend-v2 --rollback
scale指令:擴容或縮容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod數量
scale也可以指定多個前提條件,如:目前副本數量或 --resource-version ,進行伸縮比例設定前,系統會先驗證前提條件是否成立。這個就是彈性伸縮政策
# 文法
kubectl scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)
# 将名為foo中的pod副本數設定為3。
kubectl scale --replicas=3 rs/foo
kubectl scale deploy/nginx --replicas=30
# 将由“foo.yaml”配置檔案中指定的資源對象和名稱辨別的Pod資源副本設為3
kubectl scale --replicas=3 -f foo.yaml
# 如果目前副本數為2,則将其擴充至3。
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
# 設定多個RC中Pod副本數量
kubectl scale --replicas=5 rc/foo rc/bar rc/baz
autoscale指令:
這個比scale更加強大,也是彈性伸縮政策 ,它是根據流量的多少來自動進行擴充或者縮容
指定Deployment、ReplicaSet或ReplicationController,并建立已經定義好資源的自動伸縮器。使用自動伸縮器可以根據需要自動增加或減少系統中部署的pod數量。
# 文法
kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]
# 使用 Deployment “foo”設定,使用預設的自動伸縮政策,指定目标CPU使用率,使其Pod數量在2到10之間
kubectl autoscale deployment foo --min=2 --max=10
# 使用RC“foo”設定,使其Pod的數量介于1和5之間,CPU使用率維持在80%
kubectl autoscale rc foo --max=5 --cpu-percent=80
7、叢集管理指令:certificate、cluster-info、top、cordon、uncordon、drain、taint
certificate指令:用于證書資源管理,授權等
root@k8s-master:~# kubectl certificate --help
Modify certificate resources.
Available Commands:
approve Approve a certificate signing request
deny Deny a certificate signing request
Usage:
kubectl certificate SUBCOMMAND [options]
Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
# 例如,當有node節點要向master請求,那麼是需要master節點授權的
kubectl certificate approve node-csr-81F5uBehyEyLWco5qavBsxc1GzFcZk3aFM3XW5rT3mw node-csr-Ed0kbFhc_q7qx14H3QpqLIUs0uKo036O2SnFpIheM18
cluster-info指令:顯示叢集資訊
root@k8s-master:~# kubectl cluster-info
Kubernetes control plane is running at https://127.0.0.1:6443
CoreDNS is running at https://127.0.0.1:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
top指令:用于檢視資源的cpu,記憶體磁盤等資源的使用率
kubectl top pod --all-namespaces
它需要heapster運作才行
cordon指令:用于标記某個節點不可排程
uncordon指令:用于标簽節點可以排程
drain指令: 用于在維護期間排除節點。
taint指令:給某個Node節點設定污點
8、叢集故障排查和調試指令:describe、logs、exec、cp
describe指令:顯示特定資源的詳細資訊
# 文法
kubectl describe TYPE NAME_PREFIX
(首先檢查是否有精确比對TYPE和NAME_PREFIX的資源,如果沒有,将會輸出所有名稱以NAME_PREFIX開頭的資源詳細資訊)
支援的資源包括但不限于(大小寫不限):pods (po)、services (svc)、 replicationcontrollers (rc)、nodes (no)、events (ev)、componentstatuses (cs)、 limitranges (limits)、persistentvolumes (pv)、persistentvolumeclaims (pvc)、 resourcequotas (quota)和secrets。
#檢視my-nginx pod的詳細狀态
kubectl describe po my-nginx
logs指令:用于在一個pod中列印一個容器的日志,如果pod中隻有一個容器,可以省略容器名
# 文法
kubectl logs [-f] [-p] POD [-c CONTAINER]
# 傳回僅包含一個容器的pod nginx的日志快照
$ kubectl logs nginx
# 傳回pod ruby中已經停止的容器web-1的日志快照
$ kubectl logs -p -c ruby web-1
# 持續輸出pod ruby中的容器web-1的日志
$ kubectl logs -f -c ruby web-1
# 僅輸出pod nginx中最近的20條日志
$ kubectl logs --tail=20 nginx
# 輸出pod nginx中最近一小時内産生的所有日志
$ kubectl logs --since=1h nginx
# 參數選項
-c, --container="": 容器名。
-f, --follow[=false]: 指定是否持續輸出日志(實時日志)。
--interactive[=true]: 如果為true,當需要時提示使用者進行輸入。預設為true。
--limit-bytes=0: 輸出日志的最大位元組數。預設無限制。
-p, --previous[=false]: 如果為true,輸出pod中曾經運作過,但目前已終止的容器的日志。
--since=0: 僅傳回相對時間範圍,如5s、2m或3h,之内的日志。預設傳回所有日志。隻能同時使用since和since-time中的一種。
--since-time="": 僅傳回指定時間(RFC3339格式)之後的日志。預設傳回所有日志。隻能同時使用since和since-time中的一種。
--tail=-1: 要顯示的最新的日志條數。預設為-1,顯示所有的日志。
--timestamps[=false]: 在日志中包含時間戳
exec指令:進入容器進行互動,在容器中執行指令
#文法
kubectl exec POD [-c CONTAINER] -- COMMAND [args...]
#指令選項
-c, --container="": 容器名。如果未指定,使用pod中的一個容器。
-p, --pod="": Pod名。
-i, --stdin[=false]: 将控制台輸入發送到容器。
-t, --tty[=false]: 将标準輸入控制台作為容器的控制台輸入。
#進入nginx容器,執行一些指令操作
kubectl exec -it nginx-deployment-66666666-lc5fp bash
cp指令:拷貝檔案或者目錄到pod容器中
用于pod和外部的檔案交換,類似于docker 的cp,就是将容器中的内容和外部的内容進行交換。
root@k8s-master:~# kubectl cp --help
Copy files and directories to and from containers.
Examples:
# !!!Important Note!!!
# Requires that the 'tar' binary is present in your container
# image. If 'tar' is not present, 'kubectl cp' will fail.
#
# For advanced use cases, such as symlinks, wildcard expansion or
# file mode preservation, consider using 'kubectl exec'.
# Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar xf - -C /tmp/bar
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl exec -n <some-namespace> <some-pod> -- tar cf - /tmp/foo | tar xf - -C /tmp/bar
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
# Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
# Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
Options:
-c, --container='': Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for
selecting the container to be attached or the first container in the pod will be chosen
--no-preserve=false: The copied file/directory's ownership and permissions will not be preserved in the container
--retries=0: Set number of retries to complete a copy operation from a container. Specify 0 to disable or any
negative value for infinite retrying. The default is 0 (no retry).
Usage:
kubectl cp <file-spec-src> <file-spec-dest> [options]
9、其他指令:api-servions、apply
api-servions指令:列印受支援的api版本資訊
root@k8s-master:~# kubectl api-versions
admissionregistration.k8s.io/v1
apiextensions.k8s.io/v1
apiregistration.k8s.io/v1
apps/v1
authentication.k8s.io/v1
authorization.k8s.io/v1
autoscaling/v1
autoscaling/v2
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
coordination.k8s.io/v1
discovery.k8s.io/v1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
flowcontrol.apiserver.k8s.io/v1beta2
networking.k8s.io/v1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
scheduling.k8s.io/v1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
#更詳細的api資訊
root@k8s-master:~# kubectl api-resources
apply指令:通過檔案名或者标準輸入對資源應用配置通過檔案名或控制台輸入,對資源進行配置。 如果資源不存在,将會建立一個。可以使用 JSON 或者 YAML 格式。
文法
kubectl apply -f FILENAME
kubectl apply -f test.yaml