kubectl 命令大全

 

1、查看上下文

# 展示kubernet集群的配置设置信息

kubectl config view

 

# use multiple kubeconfig files at the same time and view merged config

KUBECONFIG=~/.kube/config:~/.kube/kubconfig2

 

# 获取e2e用户的密码

kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'

 

#获取用户列表

kubectl config view -o jsonpath='{.users[].name}'   

 

#展示上下文列表

kubectl config get-contexts                       

 

#展示当前上下文

kubectl config current-context                        

 

#设置默认上下文为my-cluster-name

kubectl config use-context my-cluster-name         

 

# 通过验证添加一个新的分支进集群

kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword

 

# 将后续kubectl 的命令永久保存到该上下文所有的命名空间

kubectl config set-context --current --namespace=ggckad-s2

 

# 使用特定的用户名和命名空间设置上下文

kubectl config set-context gce --user=cluster-admin --namespace=foo \

  && kubectl config use-context gce

  

#删除用户foo

kubectl config unset users.foo                       # delete user foo

2、应用 , apply通过定义Kubernetes资源的文件管理应用程序。它通过运行在集群中创建和更新资源kubectl apply

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                       # get the documentation for pod and svc manifests

3、查询资源

kubectl get services                          # 展示当前namespace下所有service

kubectl get pods --all-namespaces             # 展示所有namespace下所有的pod

kubectl get pods -o wide                      # 展示所有namespace下所有的pod的更多信息

kubectl get deployment my-dep                 # 展示指定的deployment

kubectl get pods --include-uninitialized      # 展示当前namespace下所有pod,包括未初始化的

kubectl get pod my-pod -o yaml                # 获取pod的配置文件

kubectl get pod my-pod -o yaml --export       # 获取pod的配置文件,排除特定的属性

 

# 描述指定资源的详细信息

kubectl describe nodes my-node

kubectl describe pods my-pod

 

# 展示依据metadata.name 排序过的service

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

 

# 展示依据重启次数排序的pod

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

 

# 获取标签为app=cassandra的pod的metadata.labels.version

kubectl get pods --selector=app=cassandra -o \

  jsonpath='{.items[*].metadata.labels.version}'

 

# Get all worker nodes (use a selector to exclude results that have a label

# named 'node-role.kubernetes.io/master')

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

 

# 获取当前命名空间下正在运行的Pod

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

 

# 获取所有node的ExtenalIP地址

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

 

# 列出属于特定RC的Pod名称

#jq命令对于复杂的json路径转换很有用, 更多详情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对象)的标签

# Also uses "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/nullprintf "\n"done

 

# 或者也可以使用此命令获取与pod关联的所有标签

kubectl get pods --show-labels

 

# 检查哪些节点已准备就绪

JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \

 && kubectl get nodes -o jsonpath="$JSONPATH" grep "Ready=True"

 

# 列出当前pod正在使用的所有secert

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

 

# 展示根据时间标签排序的事件

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

4、更新资源

kubectl set image deployment/frontend www=image:v2               # 滚动更新容器"www"的"frontend"deployment,并且更新镜像

kubectl rollout undo deployment/frontend                         # 回退到上一个版本的deploymeny

kubectl rollout status -w deployment/frontend                    # 滚动观察frontend 部署情况,直到完成

 

# 不建议使用的

kubectl rolling-update frontend-v1 -f frontend-v2.json           # (deprecated) Rolling update pods of frontend-v1

kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2  # (deprecated) Change the name of the resource and update the image

kubectl rolling-update frontend --image=image:v2                 # (deprecated) Update the pods image of frontend

kubectl rolling-update frontend-v1 frontend-v2 --rollback        # (deprecated) Abort existing rollout in progress

 

cat pod.json | kubectl replace -f -                              # Replace a pod based on the JSON passed into std

 

#  强制替换,删除然后重建资源,这个操作会导致服务中断

kubectl replace --force -f ./pod.json

 

# 为rc管理的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

5、修改资源

kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' # 更新部分节点

 

# 更新容器镜像:容器名是必须的,通过名字来进行合并

kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

 

# 使用json数组来更新容器的镜像

kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

 

# 通过json数组来禁用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" } }]'

6、编辑资源(重新加载,热加载的方式)

kubectl edit svc/docker-registry                      # 编辑一个docker-registry的服务

KUBE_EDITOR="nano" kubectl edit svc/docker-registry   # 使用替代编辑器

7、扩展资源

kubectl scale --replicas=3 rs/foo                                 # 将一个名为foo的资源副本变为3

kubectl scale --replicas=3 -f foo.yaml                            # 将foo.yml中指定的资源变为3

kubectl scale --current-replicas=2 --replicas=3 deployment/mysql  # 如果名为mysql的deployment当前副本为2,则扩展为3

kubectl scale --replicas=5 rc/foo rc/bar rc/baz                   # 控制多个rc 变为5个

8、删除资源

kubectl delete -f ./pod.json                                              # 通过特定的pod.json 删除pod

kubectl delete pod,service baz foo                                        # 删除名字为baz和foo的pods和services

kubectl delete pods,services -l name=myLabel                              # 删除label为myLabel的pods和services

kubectl delete pods,services -l name=myLabel --include-uninitialized      # 删除label为myLabel并且没有初始化的pods和services

kubectl -n my-ns delete po,svc --all                                      # 删除my-ns命名空间下的所有未初始化的pods和services

 

# 删除与pattern1和pattern2匹配的pods

kubectl get pods  -n mynamespace --no-headers=true awk '/pattern1|pattern2/{print $1}' xargs  kubectl delete -n mynamespace pod

9、与正在运行的pod交互

kubectl logs my-pod                                 # dump pod的日志(控制台输出)

kubectl logs -l name=myLabel                        # dump label为myLabel的pod的日志(控制台输出)

kubectl logs my-pod --previous                      # dump pod 前一个版本容器实例化的日志(控制台输出)

kubectl logs my-pod -c my-container                 # dump pod的容器日志

kubectl logs -l name=myLabel -c my-container        # dump label为myLabel的pod的日志(控制台输出)

kubectl logs my-pod -c my-container --previous      # dump pod 前一个版本容器实例化的日志(控制台输出)

kubectl logs -f my-pod                              # dump pod的日志(控制台输出)

kubectl logs -f my-pod -c my-container              # dump pod的容器日志

kubectl logs -f -l name=myLabel --all-containers    # dump 所有标签为myLabel的pod所有日志

kubectl run -i --tty busybox --image=busybox -- sh  # 将pod作为交互式shell运行

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及其容器的metrics

10、与节点集群交互

kubectl cordon my-node                                                # 将my-node标记为不可调度

kubectl drain my-node                                                 # 清空my-node以准备维护

kubectl uncordon my-node                                              # 将my-node标记为可调度

kubectl top node my-node                                              # 展示指定my-node的metrics

kubectl cluster-info                                                  # 展示master节点以及services的地址

kubectl cluster-info dump                                             # dump 当前集群分支的状态

kubectl cluster-info dump --output-directory=/path/to/cluster-state   # dump 当前集群分支的状态到/path/to/cluster-state

 

# 如果已存在具有该key和效果的属性,则其值将按指定替换。

kubectl taint nodes foo dedicated=special-user:NoSchedule

11、资源类型

kubectl api-resources 列出所有支持的资源类型及其短名称,API组,是否为命名空间,以及Kind

 

 

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       # 支持“list”和“get”请求动词的所有资源

kubectl api-resources --api-group=extensions # “extensions”API组中的所有资源

格式化输出

输出格式

描述

-o=custom-columns= 使用逗号分隔的自定义列列表打印表
-o=custom-columns-file= 使用文件中的自定义列模板打印表
-o=json 输出JSON格式的API对象
-o=jsonpath=