kubectl命令的用法

说明

  • Kubernetes版本为v1.14.8
  • 某些功能在更高的版本才会有,会做特殊说明
  • 低版本不管!

QuickStart

获取帮助

1
kubectl --help

查看集群信息

1
kubectl cluster-info

指定kubeconfig

默认是当前用户家目录下的~/.kube/config

1
kubectl --config /path/to/kubeconfig

kubeconfig上下文配置

1
2
3
4
5
6
7
8
# 查看kubeconfig信息
kubectl config view
# 合并多个kubeconfig文件并查看合并后的kubeconfig信息
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view
# 显示当前上下文
kubectl config current-context
# 设置默认上下文为cluster-name
kubectl config use-context cluster-name

指定命名空间

默认命名空间是default

1
2
kubectl --namespace kube-system
kubectl -n kube-system

指定所有命名空间

1
kubectl --all-namespaces

指定输出格式

默认不带任何输出参数时,是以较短结果输出

1
2
3
4
5
kubectl get pod
kubectl get pod --output=wide
kubectl get pod -o wide
kubectl get pod -o json
kubectl get pod -o yaml

输出结果排序

默认是以Pod名字排序

可以通过指定--sort-by来做排序

例如让Pod以宿主机名称排序

1
kubectl get pod -n kube-system -o wide --sort-by="{.spec.nodeName}"

测试yaml文件,实际不生效

1
kubectl apply -f demo.yaml --dry-run

生成模板文件

yaml文件内容字段比较多,很难一下子想到所需的字段,可以通过kubectl命令来生成对应的模板

下面以deployment为例

1
kubectl -n kube-system get deployment coredns -o yaml --export

输出示例

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: null
generation: 1
labels:
k8s-app: kube-dns
name: coredns
selfLink: /apis/extensions/v1beta1/namespaces/kube-system/deployments/coredns
spec:
progressDeadlineSeconds: 600
replicas: 2
revisionHistoryLimit: 10
selector:
matchLabels:
k8s-app: kube-dns
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 1
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
k8s-app: kube-dns
spec:
containers:
- args:
- -conf
- /etc/coredns/Corefile
image: gcr.azk8s.cn/google_containers/coredns:1.3.1
imagePullPolicy: IfNotPresent
livenessProbe:
failureThreshold: 5
httpGet:
path: /health
port: 8080
scheme: HTTP
initialDelaySeconds: 60
periodSeconds: 10
successThreshold: 1
timeoutSeconds: 5
name: coredns
ports:
- containerPort: 53
name: dns
protocol: UDP
- containerPort: 53
name: dns-tcp
protocol: TCP
- containerPort: 9153
name: metrics
protocol: TCP
readinessProbe:
failureThreshold: 3
httpGet:
path: /health
port: 8080
scheme: HTTP
periodSeconds: 10
successThreshold: 1
timeoutSeconds: 1
resources:
limits:
memory: 170Mi
requests:
cpu: 100m
memory: 70Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
add:
- NET_BIND_SERVICE
drop:
- all
readOnlyRootFilesystem: true
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /etc/coredns
name: config-volume
readOnly: true
- mountPath: /tmp
name: tmp
dnsPolicy: Default
nodeSelector:
beta.kubernetes.io/os: linux
priorityClassName: system-cluster-critical
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: coredns
serviceAccountName: coredns
terminationGracePeriodSeconds: 30
tolerations:
- key: CriticalAddonsOnly
operator: Exists
- effect: NoSchedule
key: node-role.kubernetes.io/master
volumes:
- emptyDir: {}
name: tmp
- configMap:
defaultMode: 420
items:
- key: Corefile
path: Corefile
name: coredns
name: config-volume
status: {}

创建资源

1
2
3
4
5
6
7
8
# 声明yaml定义的资源
kubectl apply -f /path/to/yaml
# 删除pod
kubectl delete pod busybox
# 删除带k8s-app: busybox标签的pod
kubectl delete pod -l k8s-app=busybox
# 删除所有pod
kubectl delete pod --all

编辑资源

1
2
3
4
# 编辑名为CoreDNS的configmaps
kubectl edit -n kube-system configmaps coredns
# 设置kube的编辑器
KUBE_EDITOR="nano" kubectl edit configmaps coredns

kubectl cheatsheet

自动补全

bash

1
2
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc

zsh

1
2
source <(kubectl completion zsh)
echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc

上下文配置

查看kubeconfig配置

1
kubectl config view

配置多kubeconfig

1
2
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view

查看上下文清单

1
kubectl config get-contexts

查看当前上下文

1
kubectl config current-context

切换默认上下文

1
kubectl config use-context my-cluster-name

创建k8s对象

创建资源

根据文件创建

1
2
3
4
5
kubectl apply -n NAMESPACE -f /path/to/yamlfile
kubectl apply -n NAMESPACE -f /path/to/yamlfile1 -f /path/to/yamlfile2
kubectl apply -n NAMESPACE -f /path/to/yamlfile_dir
kubectl apply -n NAMESPACE -f http://website/yamlfile
kubectl create deployment nginx --images=nginx

通过stdin创建

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
36
37
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep
spec:
containers:
- name: busybox
image: busybox
args:
- sleep
- "1000000"
---
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep-less
spec:
containers:
- name: busybox
image: busybox
args:
- sleep
- "1000"
EOF


cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: $(echo -n "s33msi4" | base64 -w0)
username: $(echo -n "jane" | base64 -w0)
EOF

查看资源信息

查看多个kind资源

1
kubectl get pod,svc

查看所有命名空间

1
kubectl get pod --all-namespaces

设置命令输出格式

1
2
3
kubectl get pod -o wide
kubectl get pod -o yaml
kubectl get pod -o yaml --export

描述资源信息

1
2
kubectl describe node k8s-node1
kubectl describe pod kube-apiserver-k8s-master

根据名字排序

1
kubectl get services --sort-by=.metadata.name

只获取资源名字

1
kubectl get deployments -o jsonpath='{.items[*].metadata.name}'

根据Pod重启次数排序

1
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

根据PV大小排序

1
kubectl get pv -n test --sort-by=.spec.capacity.storage

根据时间戳排序

1
kubectl get events --sort-by=.metadata.creationTimestamp

根据label筛选

1
kubectl get pods --selector=app=cassandra

获取版本label

1
2
3
4
kubectl get pods \
--selector=app=cassandra \
-o \
jsonpath='{.items[*].metadata.labels.version}'

获取非master的节点

1
kubectl get node --selector='!node-role.kubernetes.io/master'

获取运行状态为Running的Pod

1
kubectl get pods --field-selector=status.phase=Running

获取节点的ExternalIP

1
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

列出Pod的label

1
kubectl get pods --show-labels

列出ready状态的node

1
2
JSONPATH="{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}"
kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"

列出被Pod使用的Secret

1
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq

查看diff

1
kubectl diff -f /path/to/yamlfile

查看异常的Pod

1
kubectl get pod --all-namespaces --field-selector status.phase!=Succeeded,status.phase!=Running

这里通过go-template将退出信息也显示出来

1
2
GO_TEMPLATE='{{range .items}}{{printf "[PodName=%s]\n" .metadata.name}}{{range .status.containerStatuses}}{{if .state.terminated.exitCode}}{{printf "containerName=%-20s exitCode=%-5d reason=%-20s\n" .name .state.terminated.exitCode .state.terminated.reason}}{{end}}{{end}}{{end}}'
kubectl get pod --all-namespaces --field-selector status.phase!=Succeeded,status.phase!=Running -o go-template="${GO_TEMPLATE}"

更新资源

更新镜像

1
kubectl set image deployment/frontend www=image:v2

查看更新历史

1
kubectl rollout history deployment/frontend

回滚更新操作

1
kubectl rollout undo deployment/frontend

回滚到指定revision

1
kubectl rollout undo deployment/frontend --to-revision=2

滚动更新状态

1
kubectl rollout status -w deployment/frontend

滚动重启Pod

Kubernetes v1.15版本加入重启Pod的功能
1
kubectl rollout restart deployment/frontend

Patch资源

设置node不可调度

1
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

修改deployment副本数量

1
kubectl  patch deployments my-deploy -p '{"spec": {"replicas": 3}}'

更新Pod容器的镜像

1
2
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new imag

去除数组对象

1
2
kubectl patch deployment valid-deployment --type json \
-p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'

添加数组对象

1
2
kubectl patch sa default --type='json' \
-p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'

资源删改

编辑资源

1
2
kubectl edit svc/docker-registry
KUBE_EDITOR="nano" kubectl edit svc/docker-registry

伸缩资源

1
2
3
4
kubectl scale --replicas=3 rs/foo
kubectl scale --replicas=3 -f foo.yaml
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
kubectl scale --replicas=5 rc/foo rc/bar rc/baz

删除资源

1
2
3
4
5
kubectl delete -f ./pod.json
kubectl delete pod,service baz foo
kubectl delete pods,services -l name=myLabel
kubectl -n my-ns delete pod,svc --all
kubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace pod

与Pod交互

查看Pod日志

1
kubectl logs my-pod

根据label看Pod日志

1
kubectl logs -l name=myLabel

查看上一个Pod实例日志

1
kubectl logs my-pod --previous

查看Pod容器日志

1
kubectl logs my-pod -c my-container

查看Pod所有容器日志

1
kubectl logs my-pod --all-containers

在Pod上运行命令

1
kubectl exec my-pod -- ls /

在Pod指定容器上运行命令

1
kubectl exec my-pod -c my-container -- ls /

查看Pod metrics数据

1
2
kubectl top pod POD_NAME --containers
kubectl top pod --all-namespaces --containers=true

与Node交互

设置node不可调度

1
kubectl cordon my-node

恢复node可调度

1
kubectl uncordon my-node

驱逐node的Pod

1
kubectl drain my-node

查看node metrics数据

1
kubectl top node my-node

修改taint

1
kubectl taint nodes foo dedicated=special-user:NoSchedule

资源类型

查看资源类型

1
2
3
4
5
6
7
8
9
kubectl api-resources
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
kubectl api-resources -o name
kubectl api-resources -o wide
kubectl api-resources --verbs=list,get
kubectl api-resources --api-group=extensions
kubectl api-versions
kubectl get crd

命令输出格式

Output formatDescription
-o=custom-columns=Print a table using a comma separated list of custom columns
-o=custom-columns-file=Print a table using the custom columns template in the file
-o=jsonOutput a JSON formatted API object
-o=jsonpath=Print the fields defined in a jsonpath expression
-o=jsonpath-file=Print the fields defined by the jsonpath expression in the file
-o=namePrint only the resource name and nothing else
-o=wideOutput in the plain-text format with any additional information, and for pods, the node name is included
-o=yamlOutput a YAML formatted API object

命令输出日志级别

VerbosityDescription
--v=0Generally useful for this to always be visible to a cluster operator.
--v=1A reasonable default log level if you don’t want verbosity.
--v=2Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems.
--v=3Extended information about changes.
--v=4Debug level verbosity.
--v=6Display requested resources.
--v=7Display HTTP request headers.
--v=8Display HTTP request contents.
--v=9Display HTTP request contents without truncation of contents.

更多cheatsheets

cheatsheet-kubernetes-a4