kubectl kubernetes cheatsheet
from : https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-a4
PDF Link: cheatsheet-kubernetes-A4.pdf, Category: Cloud
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-A4
Related posts: Kubernetes Yaml, #denny-cheatsheets
My Favorite
kubectl get po -l app=cloud-wifi-optimization
kubectl -n cloud get pv,pvc,cm,ds,svc,deploy,po,ing
kubectl set image deployment/nginx nginx=xxx:8080/nginx:lastest
force delete pod: kubectl get pods | grep Terminating | awk '{print $1}' | xargs kubectl delete pod --force --grace-period=0
kubectl patch node prodca-kube-master -p '{"spec":{"unschedulable":true}}'
kubectl cordon node1
kubectl uncordon node1
根据进程pid查看该进程所属的容器
docker ps -q | xargs docker inspect --format '{{.State.Pid}}, {{.Name}}' | grep "$pid"
#查找k8s pod name
docker inspect -f "{{.Id}} {{.State.Pid}} {{.Config.Hostname}}" $(docker ps -q) |grep <PID>
#如果PID是容器内运行子进程那docker inspect就无法显示了
for i in `docker ps |grep Up|awk '{print $1}'`;do echo \ &&docker top $i &&echo ID=$i; done |grep -A 10 <PID>
kubectl - 备忘单
Kubectl 自动补全
BASH source <(kubectl completion bash) # 在 bash 中设置当前 shell 的自动补全,要先安装 bash-completion 包。 echo "source <(kubectl completion bash)" >> ~/.bashrc # 在您的 bash shell 中永久的添加自动补全 您还可以为 kubectl 使用一个速记别名,该别名也可以与 completion 一起使用: alias k=kubectl complete -F __start_kubectl k ZSH source <(kubectl completion zsh) # 在 zsh 中设置当前 shell 的自动补全 echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc # 在您的 zsh shell 中永久的添加自动补全
Kubectl 上下文和配置
kubectl config view # 显示合并的 kubeconfig 配置。 # 同时使用多个 kubeconfig 文件并查看合并的配置 KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view # 获取 e2e 用户的密码 kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}' kubectl config current-context # 展示当前所处的上下文 kubectl config use-context my-cluster-name # 设置默认的上下文为 my-cluster-name # 添加新的集群配置到 kubeconf 中,使用 basic auth 进行鉴权 kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword # 使用特定的用户名和命名空间设置上下文。 kubectl config set-context gce --user=cluster-admin --namespace=foo \ && kubectl config use-context gce
Apply
apply 通过定义 Kubernetes 资源的文件管理应用程序。它通过运行 kubectl apply 在集群中创建和更新资源。这是在生产中管理 Kubernetes 应用程序的推荐方法。查阅 Kubectl 文档。
创建对象
Kubernetes 配置可以用 json 或 yaml 定义。可以使用的文件扩展名有 .yaml,.yml 和 .json。
kubectl apply -f ./my-manifest.yaml # 创建资源 kubectl apply -f ./my1.yaml -f ./my2.yaml # 使用多个文件创建 kubectl apply -f ./dir # 从目录下的全部配置文件创建资源 kubectl apply -f https://git.io/vPieo # 从 url 中创建资源 kubectl create deployment nginx --image=nginx # 启动单实例 nginx kubectl explain pods,svc # 获取 pod,svc 配置的文档说明 # 从标准输入中的多个 YAML 对象中创建 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 # 创建有多个 key 的 Secret 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
获取和查找资源
# 使用 get 命令获取基本输出 kubectl get services # 列出当前命名空间下的所有 services kubectl get pods --all-namespaces # 列出所有命名空间下的全部的 pods kubectl get pods -o wide # 列出当前命名空间下的全部 pods,有更多的详细信息 kubectl get deployment my-dep # 列出某个特定的 deployment kubectl get pods --include-uninitialized # 列出当前命名空间下的全部 pods,包含未初始化的 kubectl get pod my-pod -o yaml # 获取一个 pod 的 YAML kubectl get pod my-pod -o yaml --export # 获取一个没有集群特定信息的 YAML # 使用 describe 命令获取详细输出 kubectl describe nodes my-node kubectl describe pods my-pod kubectl get services --sort-by=.metadata.name # 列出当前命名空间下所有 services,按照名称排序 # 列出 pods 按照重启次数进行排序 kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # 列出测试命名空间中的 Pod,按容量排序 kubectl get pods -n test --sort-by=.spec.capacity.storage # 获取包含 app=cassandra 标签全部 pods 的 version 标签 kubectl get pods --selector=app=cassandra -o \ jsonpath='{.items[*].metadata.labels.version}' # 获取所有工作节点(使用选择器以排除标签名称为 'node-role.kubernetes.io/master' 的结果) kubectl get node --selector='!node-role.kubernetes.io/master' # 获取当前命名空间中正在运行的 pods kubectl get pods --field-selector=status.phase=Running # 获取全部 node 的 ExternalIP 地址 kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' # 列出属于某个特定 RC 的 pods 的名称 # "jq" 命令对于 jsonpath 过于复杂的转换非常有用,可以在 https://stedolan.github.io/jq/ 找到它。 sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?} echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name}) # 显示所有 Pod 的标签(或任何其他支持标签的 Kubernetes 对象) # 也可以使用 "jq" for item in $( kubectl get pod --output=name); do printf "Labels for %s\n" "$item" | grep --color -E '[^/]+$' && kubectl get "$item" --output=json | jq -r -S '.metadata.labels | to_entries | .[] | " \(.key)=\(.value)"' 2>/dev/null; printf "\n"; done # 或也可以使用此命令来获取与容器关联的所有标签 kubectl get pods --show-labels # 检查哪些节点处于 ready JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \ && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True" # 列出被一个 pod 使用的全部 secret kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq # 列出 events,按照创建时间排序 kubectl get events --sort-by=.metadata.creationTimestamp
更新资源
从版本 1.11 开始,rolling-update 已被弃用(参见 CHANGELOG-1.11.md),请使用 rollout 代替。
kubectl set image deployment/frontend www=image:v2 # 滚动更新 "frontend" deployment 的 "www" 容器镜像 kubectl rollout history deployment/frontend # 检查部署的历史记录,包括版本 kubectl rollout undo deployment/frontend # 回滚到上次部署版本 kubectl rollout undo deployment/frontend --to-revision=2 # 回滚到特定部署版本 kubectl rollout status -w deployment/frontend # Watch "frontend" deployment 的滚动升级状态直到完成 # 从 1.11 版本开始弃用 kubectl rolling-update frontend-v1 -f frontend-v2.json # (弃用) 滚动升级 frontend-v1 的 pods kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 # (弃用) 修改资源的名称并更新镜像 kubectl rolling-update frontend --image=image:v2 # (弃用) 更新 frontend 的 pods 的镜像 kubectl rolling-update frontend-v1 frontend-v2 --rollback # (弃用) 终止已经进行中的 rollout cat pod.json | kubectl replace -f - # 通过传入到标准输入的 JSON 来替换 pod # 强制进行替换,会删除然后再创建资源,会导致服务不可用。 kubectl replace --force -f ./pod.json # 为多副本的 nginx 创建服务,使用 80 端口提供服务,连接到容器的 8000 端口。 kubectl expose rc nginx --port=80 --target-port=8000 # 更新单容器 pod 的镜像标签到 v4 kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - kubectl label pods my-pod new-label=awesome # 添加标签 kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # 添加注解 kubectl autoscale deployment foo --min=2 --max=10 # 使 "foo" deployment 自动伸缩容
局部更新资源
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' # 部分更新 node #更新容器的镜像;spec.containers[*].name 是必须的。因为它是一个合并 key。 kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}' # 使用带位置数组的 json patch 更新容器的镜像 kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]' # 使用带位置数组的 json patch 禁用 deployment 的 livenessProbe kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]' # 在带位置数组中添加元素 kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'
编辑资源
kubectl edit svc/docker-registry # 编辑名为 docker-registry 的 service KUBE_EDITOR="nano" kubectl edit svc/docker-registry # 使用其他编辑器
对资源进行伸缩
kubectl scale --replicas=3 rs/foo # 将名为 'foo' 的副本集伸缩到 3 副本 kubectl scale --replicas=3 -f foo.yaml # 将在 "foo.yaml" 中的特定资源伸缩到 3 个副本 kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # 如果名为 mysql 的 deployment 的副本当前是 2,那么将它伸缩到 3 kubectl scale --replicas=5 rc/foo rc/bar rc/baz # 伸缩多个 replication controllers
删除资源
kubectl delete -f ./pod.json # 删除在 pod.json 中指定的类型和名称的 pod kubectl delete pod,service baz foo # 删除名称为 "baz" 和 "foo" 的 pod 和 service kubectl delete pods,services -l name=myLabel # 删除包含 name=myLabel 标签的 pods 和 services kubectl delete pods,services -l name=myLabel --include-uninitialized # 删除包含 label name=myLabel 标签的 pods 和 services,包括未初始化的 kubectl -n my-ns delete po,svc --all # 删除在 my-ns 命名空间中全部的 pods 和 services ,包括未初始化的 # 删除所有与 pattern1 或 pattern2 匹配的 pod kubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace pod
与运行中的 Pods 进行交互
kubectl logs my-pod # 获取 pod 日志(标准输出) kubectl logs -l name=myLabel # 获取 pod label name=myLabel 日志(标准输出) kubectl logs my-pod --previous # 获取上个容器实例的 pod 日志(标准输出) kubectl logs my-pod -c my-container # 获取 pod 的容器日志 (标准输出, 多容器的场景) kubectl logs -l name=myLabel -c my-container # 获取 label name=myLabel pod 的容器日志 (标准输出, 多容器的场景) kubectl logs my-pod -c my-container --previous # 获取 pod 的上个容器实例日志 (标准输出, 多容器的场景) kubectl logs -f my-pod # 流式输出 pod 的日志 (标准输出) kubectl logs -f my-pod -c my-container # 流式输出 pod 容器的日志 (标准输出, 多容器的场景) kubectl logs -f -l name=myLabel --all-containers # 流式输出 label name=myLabel pod 的日志 (标准输出) kubectl run -i --tty busybox --image=busybox -- sh # 以交互式 shell 运行 pod kubectl attach my-pod -i # 进入到一个运行中的容器中 kubectl port-forward my-pod 5000:6000 # 在本地计算机上侦听端口 5000 并转发到 my-pod 上的端口 6000 kubectl exec my-pod -- ls / # 在已有的 pod 中运行命令(单容器的场景) kubectl exec my-pod -c my-container -- ls / # 在已有的 pod 中运行命令(多容器的场景) kubectl top pod POD_NAME --containers # 显示给定 pod 和容器的监控数据
与节点和集群进行交互
kubectl cordon my-node # 设置 my-node 节点为不可调度 kubectl drain my-node # 对 my-node 节点进行驱逐操作,为节点维护做准备 kubectl uncordon my-node # 设置 my-node 节点为可以调度 kubectl top node my-node # 显示给定 node 的指标 kubectl cluster-info # 显示 master 和 services 的地址 kubectl cluster-info dump # 将当前集群状态输出到标准输出 kubectl cluster-info dump --output-directory=/path/to/cluster-state # 将当前集群状态输出到 /path/to/cluster-state # 如果已存在具有该键和效果的污点,则其值将按指定替换 kubectl taint nodes foo dedicated=special-user:NoSchedule
资源类型
列出全部支持的资源类型和它们的简称, API group, 无论它们是否是 namespaced, Kind。
kubectl api-resources
用于探索 API 资源的其他操作:
kubectl api-resources --namespaced=true # 所有在命名空间中的资源 kubectl api-resources --namespaced=false # 所有不在命名空间中的资源 kubectl api-resources -o name # 输出简单的所有资源(只是资源名称) kubectl api-resources -o wide # 具有扩展(又称 "wide")输出的所有资源 kubectl api-resources --verbs=list,get # 支持 "list" 和 "get" 请求动词的所有资源 kubectl api-resources --api-group=extensions # "extensions" API 组中的所有资源
格式化输出
要以特定格式将详细信息输出到终端窗口,可以将 -o 或 --output 参数添加到支持的 kubectl 命令
| 输出格式 | 描述 |
|---|---|
-o=custom-columns=<spec> |
使用逗号分隔的自定义列列表打印表格 |
-o=custom-columns-file=<filename> |
使用 <filename> 文件中的自定义列模板打印表格 |
-o=json |
输出 JSON 格式的 API 对象 |
-o=jsonpath=<template> |
打印 jsonpath 表达式中定义的字段 |
-o=jsonpath-file=<filename> |
在 <filename> 文件中打印由 jsonpath 表达式定义的字段。 |
-o=name |
仅打印资源名称而不打印任何其他内容 |
-o=wide |
使用任何其他信息以纯文本格式输出,对于 pod 来说,包含了节点名称 |
-o=yaml |
输出 YAML 格式的 API 对象 |
Kubectl 日志输出详细程度和调试
Kubectl 日志输出详细程度是通过 -v 或者 --v 来控制的,参数后跟了一个数字表示日志的级别。Kubernetes 通用的日志习惯和相关的日志级别在 这里 有相应的描述。
| 详细程度 | 描述 |
|---|---|
--v=0 |
通常对此有用,*始终*对运维人员可见。 |
--v=1 |
如果您不想要详细程度,则为合理的默认日志级别。 |
--v=2 |
有关服务的有用稳定状态信息以及可能与系统中的重大更改相关的重要日志消息。这是大多数系统的建议默认日志级别。 |
--v=3 |
有关更改的扩展信息。 |
--v=4 |
Debug 级别。 |
--v=6 |
显示请求的资源。 |
--v=7 |
显示 HTTP 请求头。 |
--v=8 |
显示 HTTP 请求内容。 |
--v=9 |
显示 HTTP 请求内容而不截断内容。 |
1.1 Common Commands
| Name | Command |
|---|---|
| Run curl test temporarily | kubectl run --rm mytest --image=yauritux/busybox-curl -it |
| Run wget test temporarily | kubectl run --rm mytest --image=busybox -it |
| Run nginx deployment with 2 replicas | kubectl run my-nginx --image=nginx --replicas=2 --port=80 |
| Run nginx pod and expose it | |
| Run nginx deployment and expose it | |
| Set namespace preference | kubectl config set-context $(kubectl config current-context) --namespace=<ns1> |
| List pods with nodes info | kubectl get pod -o wide |
| List everything | kubectl get all --all-namespaces |
| Get all services | kubectl get service --all-namespaces |
| Get all deployments | |
| Show nodes with labels | kubectl get nodes --show-labels |
| Get resources with json output | |
| Validate yaml file with dry run | kubectl create --dry-run --validate -f pod-dummy.yaml |
| Start a temporary pod for testing | kubectl run --rm -i -t --image=alpine test-$RANDOM -- sh |
| kubectl run shell command | kubectl exec -it mytest -- ls -l /etc/hosts |
| Get system conf via configmap | kubectl -n kube-system get cm kubeadm-config -o yaml |
| Get deployment yaml | kubectl -n denny-websites get deployment mysql -o yaml |
| Explain resource | kubectl explain pods, kubectl explain svc |
| Watch pods | kubectl get pods -n wordpress --watch |
| Query healthcheck endpoint | curl -L http://127.0.0.1:10250/healthz |
| Open a bash terminal in a pod | kubectl exec -it storage sh |
| Check pod environment variables | kubectl exec redis-master-ft9ex env |
| Enable kubectl shell autocompletion | echo "source <(kubectl completion bash)" >>~/.bashrc, and reload |
| Use minikube dockerd in your laptop | eval $(minikube docker-env), No need to push docker hub any more |
| Kubectl apply a folder of yaml files | kubectl apply -R -f . |
| Get services sorted by name | kubectl get services –sort-by=.metadata.name |
| Get pods sorted by restart count | kubectl get pods –sort-by=’.status.containerStatuses[0].restartCount’ |
| List pods and images | kubectl get pods -o=’custom-columns=PODS:.metadata.name,Images:.spec.containers[*].image’ |
| List all container images | list-all-images.sh |
| kubeconfig skip tls verification | skip-tls-verify.md |
| Reference | GitHub: kubernetes releases |
| Reference | minikube cheatsheet, docker cheatsheet, OpenShift CheatSheet |
1.2 Check Performance
| Name | Command |
|---|---|
| Get node resource usage | kubectl top node |
| Get pod resource usage | kubectl top pod |
| Get resource usage for a given pod | kubectl top <podname> --containers |
| List resource utilization for all containers | kubectl top pod --all-namespaces --containers=true |
1.3 Resources Deletion
| Name | Command |
|---|---|
| Delete pod | kubectl delete pod/<pod-name> -n <my-namespace> |
| Delete pod by force | kubectl delete pod/<pod-name> --grace-period=0 --force |
| Delete pods by labels | kubectl delete pod -l env=test |
| Delete deployments by labels | kubectl delete deployment -l app=wordpress |
| Delete all resources filtered by labels | kubectl delete pods,services -l name=myLabel |
| Delete resources under a namespace | kubectl -n my-ns delete po,svc --all |
| Delete persist volumes by labels | kubectl delete pvc -l app=wordpress |
| Delete statefulset only (not pods) | kubectl delete sts/<stateful_set_name> --cascade=false |
1.4 Log & Conf Files
| Name | Comment |
|---|---|
| Config folder | /etc/kubernetes/ |
| Certificate files | /etc/kubernetes/pki/ |
| Credentials to API server | /etc/kubernetes/kubelet.conf |
| Superuser credentials | /etc/kubernetes/admin.conf |
| kubectl config file | ~/.kube/config |
| Kubernets working dir | /var/lib/kubelet/ |
| Docker working dir | /var/lib/docker/, /var/log/containers/ |
| Etcd working dir | /var/lib/etcd/ |
| Network cni | /etc/cni/net.d/ |
| Log files | /var/log/pods/ |
| log in master node | /var/log/kube-apiserver.log, kube-scheduler.log, kube-controller-manager.log |
| log in worker node | /var/log/kubelet.log, kubelet-proxy.log |
| Env | /etc/systemd/system/kubelet.service.d/10-kubeadm.conf |
| Env | export KUBECONFIG=/etc/kubernetes/admin.conf |
1.5 Pod
| Name | Command |
|---|---|
| List all pods | kubectl get pods |
| List pods for all namespace | kubectl get pods -all-namespaces |
| List all critical pods | kubectl get -n kube-system pods -a |
| List pods with more info | kubectl get pod -o wide, kubectl get pod/<pod-name> -o yaml |
| Get pod info | kubectl describe pod/srv-mysql-server |
| List all pods with labels | kubectl get pods --show-labels |
| List running pods | kubectl get pods –field-selector=status.phase=Running |
| Get Pod initContainer status | kubectl get pod --template '{{.status.initContainerStatuses}}' <pod-name> |
| kubectl run command | kubectl exec -it -n “$ns” “$podname” – sh -c “echo $msg >>/dev/err.log” |
| Watch pods | kubectl get pods -n wordpress --watch |
| Get pod by selector | podname=$(kubectl get pods -n $namespace –selector=”app=syslog” -o jsonpath='{.items[*].metadata.name}’) |
| List pods and containers | kubectl get pods -o=’custom-columns=PODS:.metadata.name,CONTAINERS:.spec.containers[*].name’ |
| List pods, containers and images | kubectl get pods -o=’custom-columns=PODS:.metadata.name,CONTAINERS:.spec.containers[*].name,Images:.spec.containers[*].image’ |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.6 Label & Annontation
| Name | Command |
|---|---|
| Filter pods by label | kubectl get pods -l owner=denny |
| Manually add label to a pod | kubectl label pods dummy-input owner=denny |
| Remove label | kubectl label pods dummy-input owner- |
| Manually add annonation to a pod | kubectl annotate pods dummy-input my-url=https://dennyzhang.com |
1.7 Deployment & Scale
| Name | Command |
|---|---|
| Scale out | kubectl scale --replicas=3 deployment/nginx-app |
| online rolling upgrade | kubectl rollout app-v1 app-v2 --image=img:v2 |
| Roll backup | kubectl rollout app-v1 app-v2 --rollback |
| List rollout | kubectl get rs |
| Check update status | kubectl rollout status deployment/nginx-app |
| Check update history | kubectl rollout history deployment/nginx-app |
| Pause/Resume | kubectl rollout pause deployment/nginx-deployment, resume |
| Rollback to previous version | kubectl rollout undo deployment/nginx-deployment |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates, Link: Pausing and Resuming a Deployment |
1.8 Quota & Limits & Resource
| Name | Command |
|---|---|
| Customize resource definition | kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi |
| List Resource Quota | kubectl get resourcequota |
| List Limit Range | kubectl get limitrange |
| Customize resource definition | kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.9 Service
| Name | Command |
|---|---|
| List all services | kubectl get services |
| List service endpoints | kubectl get endpoints |
| Get service detail | kubectl get service nginx-service -o yaml |
| Get service cluster ip | kubectl get service nginx-service -o go-template='{{.spec.clusterIP}}’ |
| Get service cluster port | kubectl get service nginx-service -o go-template='{{(index .spec.ports 0).port}}’ |
| Expose deployment as lb service | kubectl expose deployment/my-app --type=LoadBalancer --name=my-service |
| Expose service as lb service | kubectl expose service/wordpress-1-svc --type=LoadBalancer --name=wordpress-lb |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.10 Secrets
| Name | Command |
|---|---|
| List secrets | kubectl get secrets --all-namespaces |
| Create secret from cfg file | kubectl create secret generic db-user-pass --from-file./username.txt= |
| Generate secret | echo -n 'mypasswd', then redirect to base64 -decode |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.11 StatefulSet
| Name | Command |
|---|---|
| List statefulset | kubectl get sts |
| Delete statefulset only (not pods) | kubectl delete sts/<stateful_set_name> --cascade=false |
| Scale statefulset | kubectl scale sts/<stateful_set_name> --replicas=5 |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.12 Volumes & Volume Claims
| Name | Command |
|---|---|
| List storage class | kubectl get storageclass |
| Check the mounted volumes | kubectl exec storage ls /data |
| Check persist volume | kubectl describe pv/pv0001 |
| Copy local file to pod | kubectl cp /tmp/my <some-namespace>/<some-pod>:/tmp/server |
| Copy pod file to local | kubectl cp <some-namespace>/<some-pod>:/tmp/server /tmp/my |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.13 Events & Metrics
| Name | Command |
|---|---|
| View all events | kubectl get events --all-namespaces |
| List Events sorted by timestamp | kubectl get events –sort-by=.metadata.creationTimestamp |
1.14 Node Maintenance
| Name | Command |
|---|---|
| Mark node as unschedulable | kubectl cordon $NDOE_NAME |
| Mark node as schedulable | kubectl uncordon $NDOE_NAME |
| Drain node in preparation for maintenance | kubectl drain $NODE_NAME |
1.15 Namespace & Security
| Name | Command |
|---|---|
| List authenticated contexts | kubectl config get-contexts, ~/.kube/config |
| Load context from config file | kubectl get cs --kubeconfig kube_config.yml |
| Switch context | kubectl config use-context <cluster-name> |
| Delete the specified context | kubectl config delete-context <cluster-name> |
| List all namespaces defined | kubectl get namespaces |
| Set namespace preference | kubectl config set-context $(kubectl config current-context) --namespace=<ns1> |
| List certificates | kubectl get csr |
| Kubernetes Yaml Examples | Link: kubernetes yaml templates |
1.16 Network
| Name | Command |
|---|---|
| Temporarily add a port-forwarding | kubectl port-forward redis-izl09 6379 |
| Add port-forwaring for deployment | kubectl port-forward deployment/redis-master 6379:6379 |
| Add port-forwaring for replicaset | kubectl port-forward rs/redis-master 6379:6379 |
| Add port-forwaring for service | kubectl port-forward svc/redis-master 6379:6379 |
| Get network policy | kubectl get NetworkPolicy |
1.17 Patch
| Name | Summary |
|---|---|
| Patch service to loadbalancer | kubectl patch svc "$APP_INSTANCE_NAME-grafana" -p '{"spec": {"type": "LoadBalancer"}}' |
1.18 Extenstions
1.19 Components & Services
1.19.1 Services on Master Nodes
| Name | Summary |
|---|---|
| kube-apiserver | exposes the Kubernetes API from master nodes |
| etcd | reliable data store for all k8s cluster data |
| kube-scheduler | schedule pods to run on selected nodes |
| kube-controller-manager | node controller, replication controller, endpoints controller, and service account & token controllers |
1.19.2 Services on Worker Nodes
| Name | Summary |
|---|---|
| kubelet | makes sure that containers are running in a pod |
| kube-proxy | perform connection forwarding |
| Container Runtime | Kubernetes supported runtimes: Docker, rkt, runc and any OCI runtime-spec implementation. |
1.19.3 Addons: pods and services that implement cluster features
| Name | Summary |
|---|---|
| DNS | serves DNS records for Kubernetes services |
| Web UI | a general purpose, web-based UI for Kubernetes clusters |
| Container Resource Monitoring | collect, store and serve container metrics |
| Cluster-level Logging | save container logs to a central log store with search/browsing interface |
1.19.4 Tools
| Name | Summary |
|---|---|
| kubectl | the command line util to talk to k8s cluster |
| kubeadm | the command to bootstrap the cluster |
| kubefed | the command line to control a Kubernetes Cluster Federation |
| Kubernetes Components | Link: Kubernetes Components |
浙公网安备 33010602011771号