开发手册 欢迎您!
软件开发者资料库

Kubernetes(K8s) kubectl exec 常用命令

Kubernetes(K8s)中使用Kubectl 命令行工具管理 Kubernetes 集群。 kubectl 在 $HOME/.kube 目录中查找一个名为 config 的配置文件。 可以通过设置 KUBECONFIG 环境变量或设置 --kubeconfig 参数来指定其它 kubeconfig 文件。本文主要介绍Kubernetes(K8s)中kubectl exec 常用命令。

1、Kubectl语法

kubectl exec POD [-c CONTAINER] -- COMMAND [args...]

kubectl execexec命令dockerexec命令差不多,为在一个已经运行的容器中执行一条shell命令,如果一个pod容器中,有多个容器,需要使用-c选项指定容器。

2、kubectl命令中的简写

kubectl命令中可以使用的缩写,具体如下:

certificatesigningrequests (缩写 csr)componentstatuses (缩写 cs)configmaps (缩写 cm)customresourcedefinition (缩写 crd)daemonsets (缩写 ds)deployments (缩写 deploy)endpoints (缩写 ep)events (缩写 ev)horizontalpodautoattachrs (缩写 hpa)ingresses (缩写 ing)limitranges (缩写 limits)namespaces (缩写 ns)networkpolicies (缩写 netpol)nodes (缩写 no)persistentvolumeclaims (缩写 pvc)persistentvolumes (缩写 pv)poddisruptionbudgets (缩写 pdb)pods (缩写 po)podsecuritypolicies (缩写 psp)replicasets (缩写 rs)replicationcontrollers (缩写 rc)resourcequotas (缩写 quota)serviceaccounts (缩写 sa)services (缩写 svc)statefulsets (缩写 sts)storageclasses (缩写 sc)

3、kubectl exec 命令

常用格式:

kubectl exec -it podName  -c  containerName -n namespace -- shell comand

注意:

shell命令前,要加-- 号,否则shell命令中的参数,不能识别

1)通过kubectl exec在容器中创建目录

kubectl exec -it nginx-master-asjl -c nginx-master -n nginx  -- mkdir -p /usr/local/nginx 

2)在 pod 外执行容器中echo 命令

kubectl exec -n my-namespace my-pod -- echo hello 

3)在 pod 外查看容器中的进程信息

kubectl exec my-pod --bash -c 'ps -ef| grep hello'

4)获取命名空间下的POD,进行批量执行

kubectl get pods -o name -n your-namespace |grep -v "demo\|hello" | xargs -I{} kubectl -n your-namespace exec {} -- bash -c  'ps ux|grep ng'