| source <(kubectl completion bash) |
| source <(kubectl completion zsh) |
1、设置别名
| $ alias k=kubectl |
| $ k get po |
| NAME READY STATUS RESTARTS AGE |
| mypod 1/1 Running 18 43h |
2、使用缩写
下表列出的是 kubernetes 中所有支持的类型和缩写的别名。
资源类型 |
缩写别名 |
clusters |
|
componentstatuses |
cs |
configmaps |
cm |
daemonsets |
ds |
deployments |
deploy |
endpoints |
ep |
event |
ev |
horizontalpodautoscalers |
hpa |
ingresses |
ing |
jobs |
|
limitranges |
limits |
namespaces |
ns |
networkpolicies |
|
nodes |
no |
statefulsets |
|
persistentvolumeclaims |
pvc |
persistentvolumes |
pv |
pods |
po |
podsecuritypolicies |
psp |
podtemplates |
|
replicasets |
rs |
replicationcontrollers |
rc |
resourcequotas |
quota |
cronjob |
|
secrets |
|
serviceaccount |
sa |
services |
svc |
storageclasses |
|
thirdpartyresources |
|
记不住,用这个来查
| NAME SHORTNAMES APIGROUP NAMESPACED KIND |
| bindings true Binding |
| componentstatuses cs false ComponentStatus |
| configmaps cm true ConfigMap |
| endpoints ep true Endpoints |
| events ev true Event |
| limitranges limits true LimitRange |
| namespaces ns false Namespace |
| nodes no false Node |
| persistentvolumeclaims pvc true PersistentVolumeClaim |
| persistentvolumes pv false PersistentVolume |
| pods po true Pod |
| podtemplates true PodTemplate |
| replicationcontrollers rc true ReplicationController |
| resourcequotas quota true ResourceQuota |
| secrets true Secret |
| serviceaccounts sa true ServiceAccount |
| services svc true Service |
| mutatingwebhookconfigurations admissionregistration.k8s.io false MutatingWebhookConfiguration |
| validatingwebhookconfigurations admissionregistration.k8s.io false ValidatingWebhookConfiguration |
| customresourcedefinitions crd,crds apiextensions.k8s.io false CustomResourceDefinition |
| apiservices apiregistration.k8s.io false APIService |
| controllerrevisions apps true ControllerRevision |
| daemonsets ds apps true DaemonSet |
| deployments deploy apps true Deployment |
| replicasets rs apps true ReplicaSet |
| statefulsets sts apps true StatefulSet |
| tokenreviews authentication.k8s.io false TokenReview |
| localsubjectaccessreviews authorization.k8s.io true LocalSubjectAccessReview |
| selfsubjectaccessreviews authorization.k8s.io false SelfSubjectAccessReview |
| selfsubjectrulesreviews authorization.k8s.io false SelfSubjectRulesReview |
| subjectaccessreviews authorization.k8s.io false SubjectAccessReview |
| horizontalpodautoscalers hpa autoscaling true HorizontalPodAutoscaler |
| cronjobs cj batch true CronJob |
| jobs batch true Job |
| certificatesigningrequests csr certificates.k8s.io false CertificateSigningRequest |
| leases coordination.k8s.io true Lease |
| events ev events.k8s.io true Event |
| daemonsets ds extensions true DaemonSet |
| deployments deploy extensions true Deployment |
| ingresses ing extensions true Ingress |
| networkpolicies netpol extensions true NetworkPolicy |
| podsecuritypolicies psp extensions false PodSecurityPolicy |
| replicasets rs extensions true ReplicaSet |
| networkpolicies netpol networking.k8s.io true NetworkPolicy |
| poddisruptionbudgets pdb policy true PodDisruptionBudget |
| podsecuritypolicies psp policy false PodSecurityPolicy |
| clusterrolebindings rbac.authorization.k8s.io false ClusterRoleBinding |
| clusterroles rbac.authorization.k8s.io false ClusterRole |
| rolebindings rbac.authorization.k8s.io true RoleBinding |
| roles rbac.authorization.k8s.io true Role |
| priorityclasses pc scheduling.k8s.io false PriorityClass |
| storageclasses sc storage.k8s.io false StorageClass |
| volumeattachments storage.k8s.io false VolumeAttachment |
| kubectl get namespace |
| kubectl config set contexts.my-context.namespace my-namespace |
临时挂载宿主机上的命令
挂出来:里边的文件/文件夹挂载出来
挂进去:外边的文件/文件夹挂载进去
| $ kubectl logs my-pod |
| $ kubectl logs my-pod -c my-container |
| $ kubectl logs -f my-pod |
| $ kubectl logs -f my-pod -c my-container |
可以是pod和node
| $ kubectl top pod POD_NAME --containers |
| km top po --containers |
| POD NAME CPU(cores) MEMORY(bytes) |
| alertmanager-db86555bf-qjjcl alertmanager 3m 30Mi |
| grafana-5d85b68ff7-9kmnr grafana 1m 41Mi |
| prometheus-0 prometheus 137m 1036Mi |
| kubectl top node |
| NAME CPU(cores) CPU% MEMORY(bytes) MEMORY% |
| k8s-master01 1712m 10% 38212Mi 59% |
| k8s-master02 1378m 8% 39356Mi 61% |
| k8s-master03 2191m 13% 16503Mi 25% |
| apiVersion: v1 |
| kind: LimitRange |
| metadata: |
| name: mem-limit-range |
| spec: |
| limits: |
| - default: |
| memory: 512Mi |
| defaultRequest: |
| memory: 256Mi |
| type: Container |
| $ kubectl exec my-pod -- ls / |
| $ kubectl exec my-pod -c my-container -- ls / |
| km get pod alertmanager-db86555bf-qjjcl -o wide |
| NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES |
| alertmanager-db86555bf-qjjcl 1/1 Running 0 15d 9.130.1.28 k8s-master02 <none> <none> |
要以特定的格式向终端窗口输出详细信息,可以在 kubectl
命令中添加 -o
或者 -output
标志。
输出格式 |
描述 |
-o=custom-columns=<spec> |
使用逗号分隔的自定义列列表打印表格 |
-o=custom-columns-file=<filename> |
使用 文件中的自定义列模板打印表格 |
-o=json |
输出 JSON 格式的 API 对象 |
-o=jsonpath=<template> |
打印 jsonpath 表达式中定义的字段 |
-o=jsonpath-file=<filename> |
打印由 文件中的 jsonpath 表达式定义的字段 |
-o=name |
仅打印资源名称 |
-o=wide |
以纯文本格式输出任何附加信息,对于 Pod ,包含节点名称 |
-o=yaml |
输出 YAML 格式的 API 对象 |
使用 -v
或 --v
标志跟着一个整数来指定日志级别。
详细等级 |
描述 |
--v=0 |
总是对操作人员可见。 |
--v=1 |
合理的默认日志级别,如果您不需要详细输出。 |
--v=2 |
可能与系统的重大变化相关的,有关稳定状态的信息和重要的日志信息。这是对大多数系统推荐的日志级别。 |
--v=3 |
有关更改的扩展信息。 |
--v=4 |
调试级别详细输出。 |
--v=6 |
显示请求的资源。 |
--v=7 |
显示HTTP请求的header。 |
--v=8 |
显示HTTP请求的内容。 |
| $ kubectl cordon my-node |
| $ kubectl drain my-node |
| $ kubectl uncordon my-node |
| $ kubectl top node my-node |
| $ kubectl cluster-info |
| $ kubectl cluster-info dump |
| $ kubectl cluster-info dump --output-directory=/path/to/cluster-state |
| |
| |
| $ kubectl taint nodes foo dedicated=special-user:NoSchedule |
| kubectl cp <file-spec-src> <file-spec-dest> |
| kubectl cp <file-spec-src> <file-spec-dest> -c <specific-container> |
| kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar |
| kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar |
HostAliases:定义了 Pod 的 hosts 文件(比如 /etc/hosts)里的内容
| apiVersion: v1 |
| kind: Pod |
| ... |
| spec: |
| hostAliases: |
| |
| + ip: "10.1.2.3" |
| |
| hostnames: |
| |
| - "foo.remote" |
| - "bar.remote" |
| |
| ... |
在 Kubernetes 项目中,如果要设置 hosts 文件里的内容,一定要通过这种方法。否则,如果直接修改了 hosts 文件的话,在 Pod 被删除重建之后,kubelet 会自动覆盖掉被修改的内容。
方法一:
| |
| kubectl port-forward redis-master-765d459796-258hz 7000:6379 |
| kubectl port-forward pods/redis-master-765d459796-258hz 7000:6379 --address=10.1.1.1 |
| kubectl port-forward replicaset/redis-master 7000:6379 |
| kubectl port-forward service/redis-master 7000:redis |
输出
| Forwarding from 127.0.0.1:7000 -> 6379 |
| Forwarding from [::1]:7000 -> 6379 |
随机
| kubectl port-forward deployment/redis-master :6379 |
输出
| Forwarding from 127.0.0.1:62162 -> 6379 |
| Forwarding from [::1]:62162 -> 6379 |
方法二:
还有一种临时暴露方式是expose,这种相当于多建了一个svc
| kubectl expose svc/prometheus --type=NodePort --name=prom-np --port=9090 |
NodeSelector
Pod和Node进程绑定
| apiVersion: v1 |
| kind: Pod |
| ... |
| spec: |
| nodeSelector: |
| disktype: ssd |
这样的一个配置,意味着这个 Pod 永远只能运行在携带了“disktype: ssd”标签(Label)的节点上;否则,它将调度失败。
lifecycle 容器启停前后执行命令
| apiVersion: v1 |
| kind: Pod |
| metadata: |
| name: lifecycle-demo |
| spec: |
| containers: |
| |
| + name: lifecycle-demo-container |
| |
| image: nginx |
| lifecycle: |
| postStart: |
| exec: |
| command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"] |
| preStop: |
| exec: |
| command: ["/usr/sbin/nginx","-s","quit"] |
- postStart :在容器启动后,立刻执行一个指定的操作。需要明确的是,postStart 定义的操作,虽然是在 Docker 容器 ENTRYPOINT 执行之后,但它并不严格保证顺序。也就是说,在 postStart 启动时,ENTRYPOINT 有可能还没有结束。
当然,如果 postStart 执行超时或者错误,Kubernetes 会在该 Pod 的 Events 中报出该容器启动失败的错误信息,导致 Pod 也处于失败的状态。
- preStop: 发生的时机,则是容器被杀死之前(比如,收到了 SIGKILL 信号)。而需要明确的是,preStop 操作的执行,是同步的。所以,它会阻塞当前的容器杀死流程,直到这个 Hook 定义操作完成之后,才允许容器被杀死,这跟 postStart 不一样。
| $ 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 |
| |
| kubectl rollout history deploy prometheus -n xxx |
| REVISION CHANGE-CAUSE |
| 1 <none> |
| 2 <none> |
| 3 <none> |
| 4 <none> |
| 5 <none> |
| 6 <none> |
| 7 <none> |
| 8 <none> |
| 9 <none> |
| 10 <none> |
| 11 <none> |
| 12 <none> |
| 13 <none> |
| 14 <none> |
| 15 <none> |
| 16 <none> |
| 17 <none> |
| 18 <none> |
| 19 <none> |
| 20 <none> |
| 21 <none> |
| 22 <none> |
| 23 <none> |
| 24 <none> |
| 25 <none> |
| 26 <none> |
| 27 <none> |
查看版本3的情况
| kubectl rollout history deploy prometheus -n xxx --revision 3 |
https://cloud.google.com/kubernetes-engine/docs/how-to/updating-apps?hl=zh-cn
| $ kubectl create -f ./my-manifest.yaml |
| $ kubectl create -f ./my1.yaml -f ./my2.yaml |
| $ kubectl create -f ./dir |
| $ kubectl create -f https://git.io/vPieo |
| $ kubectl run nginx --image=nginx |
| $ kubectl explain pods,svc |
| |
| |
| $ cat <<EOF | kubectl create -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 create -f - |
| apiVersion: v1 |
| kind: Secret |
| metadata: |
| name: mysecret |
| type: Opaque |
| data: |
| password: $(echo "s33msi4" | base64) |
| username: $(echo "jane" | base64) |
| EOF |
| |
| $ kubectl get services |
| $ kubectl get pods --all-namespaces |
| $ kubectl get pods -o wide |
| $ kubectl get deployment my-dep |
| $ kubectl get pods --include-uninitialized |
| |
| |
| $ kubectl describe nodes my-node |
| $ kubectl describe pods my-pod |
| |
| $ kubectl get services --sort-by=.metadata.name |
| |
| |
| $ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' |
| |
| |
| $ kubectl get pods --selector=app=cassandra rc -o \ |
| jsonpath='{.items[*].metadata.labels.version}' |
| |
| |
| $ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' |
| |
| |
| |
| $ 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}) |
| |
| |
| $ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \ |
| && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True" |
| |
| |
| $ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq |
| $ kubectl rolling-update frontend-v1 -f frontend-v2.json |
| $ 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 |
| $ cat pod.json | kubectl replace -f - |
| |
| |
| $ kubectl replace --force -f ./pod.json |
| |
| |
| $ kubectl expose rc nginx --port=80 --target-port=8000 |
| |
| |
| $ 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 |
使用策略合并补丁并修补资源。
| $ 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"}]}}' |
| |
| |
| $ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]' |
| |
| |
| $ kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]' |
| |
在编辑器中编辑任何 API 资源。
| $ kubectl edit svc/docker-registry |
| $ KUBE_EDITOR="nano" kubectl edit svc/docker-registry |
| |
| $ kubectl delete -f ./pod.json |
| $ kubectl delete pod,service baz foo |
| $ kubectl delete pods,services -l name=myLabel |
| $ kubectl delete pods,services -l name=myLabel --include-uninitialized |
| $ kubectl -n my-ns delete po,svc --all |
| kubectl scale deployment $deployName --replicas=0 [-n $nameSpaceName] |
批量删除
| kubectl -n xxx get pods |grep prometheus | awk '{print $1}' |xargs -i kubectl -n xxx delete pod {} |
| kubectl -n xxx delete pod xx1 xx2 xx3 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步