kubectl 常用命令与操作边界
Kubernetes 命令速查
安全开场
kubectl config current-context
kubectl cluster-info
kubectl config view --minify -o jsonpath='{..namespace}{"\n"}'
kubectl auth whoami生产写操作显式带 --context=<context> -n <namespace>;先查询对象与 Owner,再 dry-run/diff。
发现与查询
kubectl api-resources --sort-by=name
kubectl explain deployment.spec.strategy --recursive
kubectl version
kubectl -n demo get pods -o wide
kubectl -n demo get deployment,service,ingress
kubectl -n demo get pods -l app=web --show-labels
kubectl -n demo get pods --field-selector=status.phase=Pending
kubectl -n demo describe pod <pod>
kubectl -n demo get events --sort-by=.lastTimestamp
kubectl get pods -A --field-selector='status.phase!=Running'应用与发布
kubectl apply --dry-run=client -f manifests/
kubectl apply --server-side --dry-run=server -f manifests/
kubectl diff -f manifests/
kubectl apply -f manifests/
kubectl -n demo set image deployment/web web=registry.example.com/web:2.4.1
kubectl -n demo rollout status deployment/web --timeout=5m
kubectl -n demo rollout history deployment/web
kubectl -n demo rollout undo deployment/web --to-revision=3
kubectl -n demo wait --for=condition=available deployment/web --timeout=5mHPA 管理的对象不要手工长期改副本;rollout undo 不回滚 ConfigMap、Secret 和数据库。
日志与调试
kubectl -n demo logs <pod> -c <container> --since=15m --timestamps
kubectl -n demo logs <pod> -c <container> --previous
kubectl -n demo exec -it <pod> -c <container> -- /bin/sh
kubectl -n demo port-forward service/web 8080:80
kubectl -n demo debug -it pod/<pod> --target=<container> \
--image=registry.k8s.io/e2e-test-images/busybox:1.29-4 --profile=general
kubectl get --raw='/readyz?verbose'exec 和临时容器是远程执行能力;节点 sysadmin 调试权限更高,必须走审批并清理。
网络与存储
kubectl -n demo get service web -o yaml
kubectl -n demo get endpointslice -l kubernetes.io/service-name=web -o wide
kubectl -n demo get ingress,httproute,networkpolicy
kubectl -n demo exec <client-pod> -- nslookup web
kubectl -n demo exec <client-pod> -- wget -S -O- http://web:80/readyz
kubectl -n demo get pvc
kubectl get pv,storageclass删除 PVC/PV 前核对 ReclaimPolicy、后端卷 ID 和可恢复备份。
调度、资源与权限
kubectl get nodes --show-labels
kubectl describe node <node>
kubectl -n demo get pods --field-selector=spec.nodeName=<node> -o wide
kubectl top nodes
kubectl -n demo describe hpa web
kubectl auth can-i --list -n demo
kubectl auth can-i get pods --as=system:serviceaccount:demo:web -n demo节点维护
node='worker-01'
kubectl get pods -A --field-selector="spec.nodeName=$node" -o wide
kubectl get pdb -A
kubectl cordon "$node"
kubectl drain "$node" --ignore-daemonsets --delete-emptydir-data --timeout=20m
# 完成维护并验证节点健康后
kubectl uncordon "$node"drain 会驱逐工作负载并删除 emptyDir 数据;不要随意用 --disable-eviction 绕过 PDB。
删除前检查
kubectl -n demo get <kind> <name> -o yaml
kubectl -n demo delete <kind> <name> --dry-run=server灾难级操作
强制零宽限删除、批量 --all 删除、删除 Namespace/PVC/PV、清空 Finalizer、直接修改 etcd 可能造成重复实例或永久数据丢失。本页不提供这些可复制命令;必须使用经审批的对象专用灾备 Runbook。
详细语义见 kubectl 基础、kubectl 进阶和排障手册。
kubectl 命令与公司 IM 日志查询
以下保留原资料的历史版本范围。
kubectl 使用
kubectl --help
user@example-host:~$ kubectl --help
kubectl controls the Kubernetes cluster manager.
Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
Basic Commands (Beginner):
create Create a resource from a file or from stdin.
expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
run Run a particular image on the cluster
set Set specific features on objects
Basic Commands (Intermediate):
explain Documentation of resources
get Display one or many resources
edit Edit a resource on the server
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector
Deploy Commands:
rollout Manage the rollout of a resource
scale Set a new size for a Deployment, ReplicaSet or Replication Controller
autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController
Cluster Management Commands:
certificate Modify certificate resources.
cluster-info Display cluster info
top Display Resource (CPU/Memory/Storage) usage.
cordon Mark node as unschedulable
uncordon Mark node as schedulable
drain Drain node in preparation for maintenance
taint Update the taints on one or more nodes
Troubleshooting and Debugging Commands:
describe Show details of a specific resource or group of resources
logs Print the logs for a container in a pod
attach Attach to a running container
exec Execute a command in a container
port-forward Forward one or more local ports to a pod
proxy Run a proxy to the Kubernetes API server
cp Copy files and directories to and from containers.
auth Inspect authorization
Advanced Commands:
diff Diff live version against would-be applied version
apply Apply a configuration to a resource by filename or stdin
patch Update field(s) of a resource using strategic merge patch
replace Replace a resource by filename or stdin
wait Experimental: Wait for a specific condition on one or many resources.
convert Convert config files between different API versions
kustomize Build a kustomization target from a directory or a remote url.
Settings Commands:
label Update the labels on a resource
annotate Update the annotations on a resource
completion Output shell completion code for the specified shell (bash or zsh)
Other Commands:
alpha Commands for features in alpha
api-resources Print the supported API resources on the server
api-versions Print the supported API versions on the server, in the form of "group/version"
config Modify kubeconfig files
plugin Provides utilities for interacting with plugins.
version Print the client and server version information
Usage:
kubectl [flags] [options]
Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
user@example-host:~$kubectl create、delete、logs
- logs
# 以下为本地教学环境,不对应真实集群
kubectl get pods -n demo
kubectl logs -n demo deployment/example-api --tail=20
# 示例日志:INFO request_id=example status=200- kubectl get namespace
$ kubectl get namespace
NAME STATUS AGE
cattle-system Active 10d
default Active 10d
kube-node-lease Active 10d
kube-public Active 10d
kube-system Active 10d
lens-metrics Active 8d
security-scan Active 10d- create、delete、replace
创建配置文件中定义的对象:
kubectl create -f nginx.yaml
删除两个配置文件中定义的对象:
kubectl delete -f nginx.yaml -f redis.yaml
通过覆盖活动配置来更新配置文件中定义的对象:
kubectl replace -f nginx.yaml公司 demo 命名空间操作命令
以下保留原资料的历史版本范围。
kubectl 命令行工具用法
语法:
kubectl [command] [type] [name] [flags]
command 子命令,用于操作集群资源对象
- create 创建
- apply
- delete 删除
- describe 详情
- get 获取
例如下
- 显示pod详情
kubectl get pod <pod-name> -n demo -o wide - 以yaml 格式显示pod详情
kubectl get pod gs-64c77d8998-6r5vf -n demo -o yaml - 自定义显示
kubectl get pod game-redis-d4cb6f5b-9khhh -n demo
test
这是原 demo 环境草稿,不是当前项目流程。全量删除、通配符和默认命名空间命令不能按整段执行;保留历史范围,通用操作以页首速查为准。
- 对资源操作 kubectl create -f deployment.yaml kubectl create -f <dir>
- 查看资源对象 kubectl get pods -n demo kubectl get rc,service,pods -n demo
- 描述资源对象 kubectl get nodes kubectl describe nodes |more kubectl describe nodes <node-name> |more
kubectl get pods --all-namespaces kubectl get pods -A kubectl get pods -n demo
kubectl describe pods <pod-name> -n demo kubectl describe rc <rc-name>
- 删除资源 kubectl delete -f *.yaml kubectl delete -f <dir> 删除所有包含某个Label的Pod和service kubectl delete pods,service -l name=<label-name> 删除所有pods kubectl delete pods --all kubectl delete pods <pod-name> -n demo
- 执行容器命令
kubectl 基础命令
kubectl
简介
- kubectl 是 Kubernetes 命令行工具,用于与 Kubernetes 集群进行交互和管理。
- 它可以用来部署应用程序,管理集群资源(例如 Pod、Service 和 ReplicaSet 等),
- 诊断和调试问题,以及执行其他与 Kubernetes 相关的任务。通过 kubectl,您可以在命令行界面中执行所有 Kubernetes API 操作,并对集群的状态进行操作。
- kubectl 是使用 Go 语言编写的开源软件,需要匹配版本的客户端、目标集群 kubeconfig、网络和所需授权;本机不必运行 Kubernetes 节点。
基础命令
下面按查询、变更与远程执行区分常用命令,占位符须替换为已确认对象。
获取集群信息:
bash# 查看 Kubernetes 集群信息 kubectl cluster-info # 查看节点列表 kubectl get nodes获取资源对象信息:
bash# 获取 Pod 列表 kubectl get pods # 获取 Service 列表 kubectl get services # 获取 Deployment 列表 kubectl get deployments # 获取 ReplicaSet 列表 kubectl get replicasets创建、更新和删除资源对象:
bash# 通过 YAML 文件创建资源对象 kubectl create -f <YAML_FILE> # 更新资源对象 kubectl apply -f <YAML_FILE> # 删除资源对象 kubectl delete -f <YAML_FILE>查看资源对象的详细信息:
bash# 查看 Pod 详细信息 kubectl describe pod <POD_NAME> # 查看 Service 详细信息 kubectl describe service <SERVICE_NAME> # 查看 Deployment 详细信息 kubectl describe deployment <DEPLOYMENT_NAME> # 查看 ReplicaSet 详细信息 kubectl describe replicaset <REPLICASET_NAME>查看 Pod 日志:
bashkubectl logs <POD_NAME>进入 Pod 中的容器:
bashkubectl exec -it <POD_NAME> -- /bin/bash扩容和缩容应用程序:
bash# 扩容 Deployment 的副本数 kubectl scale --replicas=<REPLICA_COUNT> deployment/<DEPLOYMENT_NAME> # 缩容 Deployment 的副本数 kubectl scale --replicas=<REPLICA_COUNT> deployment/<DEPLOYMENT_NAME>滚动升级应用程序:
bash# 开始滚动升级 kubectl set image deployment/<DEPLOYMENT_NAME> <CONTAINER_NAME>=<NEW_IMAGE>:<TAG> # 查看滚动升级状态 kubectl rollout status deployment/<DEPLOYMENT_NAME> # 回滚到先前的版本 kubectl rollout undo deployment/<DEPLOYMENT_NAME>
高级命令
下列包含本地监听、复制文件和 API 代理,各有相应权限与副作用。
使用 kubectl port-forward 命令将本地端口绑定到 Pod 端口:
kubectl port-forward <POD_NAME> <LOCAL_PORT>:<REMOTE_PORT>该命令会将本地端口
<LOCAL_PORT>绑定到远程 Pod 的端口<REMOTE_PORT>。例如,要将本地端口 8080 绑定到名为my-pod的 Pod 中的端口 80,可以使用以下命令:kubectl port-forward my-pod 8080:80使用 kubectl cp 命令在容器和本地文件系统之间复制文件:
kubectl cp <POD_NAME>:<CONTAINER_PATH> <LOCAL_PATH> kubectl cp <LOCAL_PATH> <POD_NAME>:<CONTAINER_PATH>该命令可以将文件从本地文件系统复制到运行中的容器中,或者将文件从容器中复制到本地文件系统中。例如,要将名为
my-pod的容器中的/app/logs目录复制到本地文件系统中的/tmp目录,可以使用以下命令:kubectl cp my-pod:/app/logs /tmp使用 kubectl top 命令查看节点和 Pod 的 CPU 和内存使用情况:
# 查看节点的 CPU 和内存使用情况 kubectl top node # 查看 Pod 的 CPU 和内存使用情况 kubectl top pod使用 kubectl proxy 命令在 Kubernetes API 服务器和本地之间建立代理:
kubectl proxy该命令会在本地启动一个代理,将 Kubernetes API 服务器和本地连接起来。通过访问
http://localhost:8001,您可以访问 Kubernetes API,并查看集群状态、部署资源等。
继续阅读
- 知识专题
- 知识专题
- 知识专题