文章目录
- [K8S 管理:kubectl 命令与集群节点运维](#K8S 管理:kubectl 命令与集群节点运维)
-
- [一、kubectl 命令语法](#一、kubectl 命令语法)
-
- [1. 与 Linux 命令的对应关系](#1. 与 Linux 命令的对应关系)
- [2. 查看帮助](#2. 查看帮助)
- 二、命令速查
-
- [1. 基础命令](#1. 基础命令)
- [2. 部署命令](#2. 部署命令)
- [3. 集群管理命令](#3. 集群管理命令)
- [4. 故障诊断与调试命令](#4. 故障诊断与调试命令)
- [5. 高级命令](#5. 高级命令)
- [6. 设置命令](#6. 设置命令)
- [7. 其他命令](#7. 其他命令)
- 三、集群与节点管理
-
- [1. 查看集群信息](#1. 查看集群信息)
- [2. 查看节点列表](#2. 查看节点列表)
- [3. 查看节点详细信息](#3. 查看节点详细信息)
- [4. 容器运行时显示 docker:// 的含义](#4. 容器运行时显示 docker:// 的含义)
- [5. 查看节点详细描述](#5. 查看节点详细描述)
- 四、metrics-server:查看资源使用率
-
- [1. 部署](#1. 部署)
- [2. 查看资源使用](#2. 查看资源使用)
- [五、故障案例:Calico 鉴权失败导致 Pod 无法创建](#五、故障案例:Calico 鉴权失败导致 Pod 无法创建)
-
- [1. 现象](#1. 现象)
- [2. 定位:查看 Pod 事件](#2. 定位:查看 Pod 事件)
- [3. 原因](#3. 原因)
- [4. 处理](#4. 处理)
- [5. 同类现象](#5. 同类现象)
- [六、worker 节点使用 kubectl 管理集群](#六、worker 节点使用 kubectl 管理集群)
-
- [1. 现象](#1. 现象)
- [2. 原因](#2. 原因)
- [3. 解决](#3. 解决)
K8S 管理:kubectl 命令与集群节点运维
!note 核心摘要
- 命令体系:kubectl 的语法结构、帮助入口,以及按功能分组的常用命令速查。
- 集群与节点管理 :查看集群/节点信息、理解
CONTAINER-RUNTIME的含义、describe节点。- 两个实践场景:metrics-server 部署与资源查看;Calico 鉴权失败导致 Pod 无法创建。
- worker 节点使用 kubectl:复制 kubeconfig,让 node 节点也能管理集群。
实验环境:kubeadm 部署的 Kubernetes v1.28.0,三节点(master + node1 + node2),容器运行时显示为
docker://26.1.4。
一、kubectl 命令语法
1. 与 Linux 命令的对应关系
集群中的管理操作基本都可以通过 kubectl 完成。它的命令结构和 Linux 命令一致,都是「命令 + 可选项 + 对象」:
| 组成 | Linux 示例 | kubectl 示例 |
|---|---|---|
| 命令(操作) | ls |
kubectl get |
| 可选项(功能) | -lh |
-o wide |
| 对象(路径) | /etc/fstab |
pod nginx |
通用格式:
bash
kubectl <命令> <资源类型> <资源名称> <参数>
例如 kubectl get pod nginx -o wide:get 是命令,pod 是资源类型,nginx 是资源名称,-o wide 是参数。
!\[03_云原生/云原生技术栈/Kubernetes/image/8c8025417efc0a0145591face169592e_MD5.jpg]
2. 查看帮助
| 命令 | 作用 |
|---|---|
kubectl -h |
查看所有子命令 |
kubectl <命令> --help |
查看单个子命令的详细用法 |
kubectl options |
查看全局参数(对所有命令生效) |
kubectl -h 把命令按用途分成了八组:
| 分组 | 包含命令 |
|---|---|
| 基础命令(入门) | create、expose、run、set |
| 基础命令(进阶) | explain、get、edit、delete |
| 部署命令 | rollout、scale、autoscale |
| 集群管理命令 | certificate、cluster-info、top、cordon、uncordon、drain、taint |
| 故障诊断与调试命令 | describe、logs、attach、exec、port-forward、proxy、cp、auth、debug、events |
| 高级命令 | diff、apply、patch、replace、wait、kustomize |
| 设置命令 | label、annotate、completion |
| 其他命令 | api-resources、api-versions、config、plugin、version |
!example- kubectl -h 原始输出(点击展开)
textkubectl controls the Kubernetes cluster manager. Find more information at: https://kubernetes.io/docs/reference/kubectl/ 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 Get documentation for a resource get Display one or many resources edit Edit a resource on the server delete Delete resources by file names, 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, replica set, or replication controller autoscale Auto-scale a deployment, replica set, stateful set, or replication controller Cluster Management Commands: certificate Modify certificate resources cluster-info Display cluster information top Display resource (CPU/memory) 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 debug Create debugging sessions for troubleshooting workloads and nodes events List events Advanced Commands: diff Diff the live version against a would-be applied version apply Apply a configuration to a resource by file name or stdin patch Update fields of a resource replace Replace a resource by file name or stdin wait Experimental: Wait for a specific condition on one or many resources kustomize Build a kustomization target from a directory or 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, zsh, fish, or powershell) Other Commands: 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).
二、命令速查
下表按 kubectl -h 的分组整理,省略了 kubectl 前缀。实际执行时需补上,例如 kubectl get nodes。
1. 基础命令
| 命令 | 说明 |
|---|---|
create |
通过文件名或标准输入创建资源 |
expose |
将资源公开为新的 Service |
run |
在集群中运行指定的镜像 |
set |
在对象上设置特定功能 |
get |
显示一个或多个资源 |
explain |
查看资源字段的文档说明 |
edit |
使用默认编辑器编辑资源 |
delete |
通过文件名、标准输入、资源名称或标签选择器删除资源 |
2. 部署命令
| 命令 | 说明 |
|---|---|
rollout |
管理资源的发布(查看状态、暂停、恢复、回滚) |
rolling-update |
对指定的 Replication Controller 滚动更新(旧版命令) |
scale |
扩容或缩容 Pod 数量,支持 Deployment、ReplicaSet、RC、Job |
autoscale |
自动扩缩容,为 Deployment、ReplicaSet、StatefulSet 等设置 Pod 数量范围 |
3. 集群管理命令
| 命令 | 说明 |
|---|---|
certificate |
修改证书资源 |
cluster-info |
显示集群信息 |
top |
显示资源(CPU、内存)使用量,依赖 metrics-server |
cordon |
标记节点为不可调度 |
uncordon |
标记节点为可调度 |
drain |
驱逐节点上的 Pod,准备下线维护 |
taint |
更新一个或多个节点上的污点 |
4. 故障诊断与调试命令
| 命令 | 说明 |
|---|---|
describe |
显示特定资源或资源组的详细信息 |
logs |
打印 Pod 中某个容器的日志;Pod 只有一个容器时可省略容器名 |
attach |
附加到一个正在运行的容器 |
exec |
在容器中执行命令 |
port-forward |
将一个或多个本地端口转发到 Pod |
proxy |
运行一个指向 Kubernetes API Server 的代理 |
cp |
在容器与本地之间拷贝文件或目录 |
auth |
检查授权 |
debug |
为工作负载或节点创建调试会话 |
events |
查看集群事件 |
5. 高级命令
| 命令 | 说明 |
|---|---|
apply |
通过文件名或标准输入应用配置(声明式,最常用) |
patch |
使用补丁修改、更新资源的字段 |
replace |
通过文件名或标准输入替换资源(命令式) |
diff |
对比集群中运行的版本与待应用的版本 |
wait |
等待一个或多个资源达到指定状态(实验性) |
kustomize |
从目录或 URL 构建 kustomization 目标 |
convert |
在不同 API 版本之间转换配置文件(旧版命令) |
6. 设置命令
| 命令 | 说明 |
|---|---|
label |
更新资源上的标签 |
annotate |
更新资源上的注解 |
completion |
生成 shell 自动补全脚本(bash、zsh、fish、powershell) |
7. 其他命令
| 命令 | 说明 |
|---|---|
api-resources |
打印服务端支持的 API 资源 |
api-versions |
打印服务端支持的 API 版本(group/version) |
config |
修改 kubeconfig 文件(如配置认证信息) |
help |
查看所有命令帮助 |
plugin |
运行命令行插件 |
version |
打印客户端和服务端版本信息 |
三、集群与节点管理
1. 查看集群信息
bash
kubectl cluster-info
输出:
text
Kubernetes control plane is running at https://192.168.100.136:6443
CoreDNS is running at https://192.168.100.136:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
2. 查看节点列表
bash
kubectl get nodes
text
NAME STATUS ROLES AGE VERSION
master Ready control-plane 17d v1.28.0
node1 Ready <none> 17d v1.28.0
node2 Ready <none> 17d v1.28.0
| 字段 | 含义 |
|---|---|
NAME |
节点名称 |
STATUS |
Ready 表示节点健康、可以接收 Pod |
ROLES |
control-plane 为控制平面节点,<none> 为工作节点 |
AGE / VERSION |
加入集群的时长 / kubelet 版本 |
3. 查看节点详细信息
bash
kubectl get nodes -o wide
text
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME
master Ready control-plane 17d v1.28.0 192.168.100.136 <none> CentOS Linux 7 (Core) 3.10.0-1160.119.1.el7.x86_64 docker://26.1.4
node1 Ready <none> 17d v1.28.0 192.168.100.128 <none> CentOS Linux 7 (Core) 3.10.0-1160.119.1.el7.x86_64 docker://26.1.4
node2 Ready <none> 17d v1.28.0 192.168.100.129 <none> CentOS Linux 7 (Core) 3.10.0-1160.119.1.el7.x86_64 docker://26.1.4
-o wide 会额外显示节点 IP 和容器运行时,排障时主要关注两列:
| 列 | 说明 |
|---|---|
INTERNAL-IP |
节点内网 IP,kubelet 与 Pod 通信使用 |
CONTAINER-RUNTIME |
容器运行时及版本,如 docker://26.1.4、containerd://1.7.x |
4. 容器运行时显示 docker:// 的含义
!note 一句话结论
docker://26.1.4表示 K8s 通过 dockershim 对接 Docker Engine(dockerd)。Docker Engine 内部虽然自带 containerd,但 K8s 访问的是 dockerd,不是这个 containerd。直接用 containerd 作为 CRI 时,显示为containerd://x.x.x。
两种接入方式的链路对比:
| 显示结果 | 接入方式 | 调用链路 |
|---|---|---|
docker://26.1.4 |
dockershim 对接 Docker | kubelet → dockershim → dockerd → containerd → runc |
containerd://1.7.x |
CRI 直接对接 containerd | kubelet → CRI → containerd → runc |
几个容易混淆的点:
- Docker Engine 26.1.4 自带一个 containerd(Docker 自己打包的),但走 dockershim 时 K8s 并不直接访问它。
- 独立部署 containerd 时,K8s 绕过 dockerd,直接与 containerd 通信。
- 两者底层最终都由 runc 启动容器,但调用链路、组件和排障命令完全不同。
为什么 v1.28 还能看到 docker://:K8s 1.24 起已移除内置 dockershim,因此还能显示 docker:// 通常说明:
- 单独部署了外部的 dockershim(如 Mirantis dockershim);
- 或者使用的是离线包/旧教程,继续以 Docker Engine 作为运行时。
面试高频:K8s 为什么弃用 dockershim?多了一层 dockerd,链路更长、故障点更多、维护成本更高。
5. 查看节点详细描述
bash
kubectl describe node master
输出较长,下面只截取开头部分:
text
Name: master
Roles: control-plane
Labels:
beta.kubernetes.io/arch=amd64
beta.kubernetes.io/os=linux
kubernetes.io/arch=amd64
kubernetes.io/hostname=master
kubernetes.io/os=linux
describe的完整输出还包含 Taints、资源容量与分配、Conditions 和 Events。节点异常时,重点看 Conditions 与 Events。
四、metrics-server:查看资源使用率
1. 部署
metrics-server 负责采集节点和 Pod 的 CPU、内存指标,kubectl top 依赖它。
在 master 上下载官方部署清单,并把镜像地址替换为阿里云镜像:
bash
wget https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml -O metrics-server-components.yaml
sed -i 's/registry.k8s.io\/metrics-server/registry.cn-hangzhou.aliyuncs.com\/google_containers/g' metrics-server-components.yaml
vim metrics-server-components.yaml
说明:
sed这一步用于替换镜像仓库,解决国内拉取registry.k8s.io镜像失败的问题。
编辑 metrics-server-components.yaml,在 args 中加入 --kubelet-insecure-tls:
!warning v0.8.0 之后必须配置 --kubelet-insecure-tls
metrics-server v0.8.0 之后安全要求提高,默认必须配置
--kubelet-insecure-tls,否则无法从 kubelet 拉取指标,导致探针失败。
yaml
containers:
- args:
- --cert-dir=/tmp
- --secure-port=10250
- --kubelet-insecure-tls # 添加
- --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
- --kubelet-use-node-status-port
- --metric-resolution=15s
image: registry.cn-hangzhou.aliyuncs.com/google_containers/metrics-server:v0.8.0
应用清单:
bash
kubectl apply -f metrics-server-components.yaml
部署后需要等待较长时间(原笔记记录约 40 分钟),期间 Pod 可能一直处于
ContainerCreating。
2. 查看资源使用
bash
kubectl top nodes # 节点 CPU / 内存
kubectl top pods -A # 所有命名空间的 Pod
能正常输出数据,说明 metrics-server 已就绪。
五、故障案例:Calico 鉴权失败导致 Pod 无法创建
1. 现象
虚拟机挂起后再恢复(解挂)时,Calico 会出现卡死状态:新建的 Pod 一直停在 ContainerCreating,无法完成网络配置。
持续观察 Pod 状态:
bash
watch -n 2 kubectl get pods -n kube-system
| NAME | READY | STATUS | RESTARTS | AGE |
|---|---|---|---|---|
| calico-kube-controllers-658d97c59c-4hkgb | 1/1 | Running | 3 (4h44m ago) | 27h |
| calico-node-8cmfp | 1/1 | Running | 0 | 27h |
| calico-node-f7mqm | 1/1 | Running | 0 | 27h |
| calico-node-tslkc | 1/1 | Running | 0 | 27h |
| coredns-66f779496c-fb7qd | 1/1 | Running | 0 | 44h |
| coredns-66f779496c-rk6xn | 1/1 | Running | 0 | 44h |
| etcd-master | 1/1 | Running | 0 | 44h |
| kube-apiserver-master | 1/1 | Running | 0 | 44h |
| kube-controller-manager-master | 1/1 | Running | 0 | 44h |
| kube-proxy-cml6g | 1/1 | Running | 0 | 44h |
| kube-proxy-tk7gl | 1/1 | Running | 0 | 44h |
| kube-proxy-tqnz5 | 1/1 | Running | 0 | 44h |
| kube-scheduler-master | 1/1 | Running | 0 | 44h |
| metrics-server-57999c5cf7-d2nhb | 0/1 | ContainerCreating | 0 | 47s |
快照中 metrics-server 的 Pod 已经调度到 node1,但仍是 0/1 ContainerCreating;calico-kube-controllers 也出现过 3 次重启。
2. 定位:查看 Pod 事件
bash
kubectl describe pod metrics-server-57999c5cf7-d2nhb -n kube-system
输出节选(重点看 Status 和 Events):
text
Name: metrics-server-57999c5cf7-d2nhb
Namespace: kube-system
Node: node1/192.168.18.129
Status: Pending
Controlled By: ReplicaSet/metrics-server-57999c5cf7
Containers:
metrics-server:
Image: registry.cn-hangzhou.aliyuncs.com/google_containers/metrics-server:v0.8.0
Port: 10250/TCP
Events:
| Type | Reason | Age | From | Message |
|---|---|---|---|---|
| Normal | Scheduled | 10m | default-scheduler | 成功调度到 node1 |
| Warning | FailedCreatePodSandBox | 10m | kubelet | Calico 创建 Pod 网络失败:connection is unauthorized: Unauthorized |
| Normal | SandboxChanged | 13s(10 分钟内 48 次) | kubelet | Pod sandbox 被反复销毁重建 |
原始报错的关键部分:
text
networkPlugin cni failed to set up pod "metrics-server-57999c5cf7-d2nhb_kube-system" network:
plugin type="calico" failed (add): error getting ClusterInformation: connection is unauthorized: Unauthorized
3. 原因
报错本质是 Calico 访问集群资源时鉴权失败 (connection is unauthorized)。Calico 读不到 ClusterInformation,就无法为 Pod 配置网络,sandbox 因此被反复重建。
原笔记中该问题出现在虚拟机挂起/恢复之后,属于 Calico 与 API Server 连接异常导致的暂时性故障。
4. 处理
方式一:重启网络服务
bash
systemctl restart NetworkManager
systemctl restart network
方式二:只重启 Calico 组件
如果判断是 Calico 的暂时性故障,可以只重启 calico-node,影响范围更小:
bash
kubectl rollout restart daemonset calico-node -n kube-system
5. 同类现象
业务 Pod 也会遇到同样的报错:
bash
kubectl describe pod deploy-nginx-66d785bdb5-jfcxt
事件序列与上面一致:Scheduled → FailedCreatePodSandBox(Calico 鉴权失败)→ SandboxChanged(反复重建)。说明问题出在 CNI 网络层,与具体业务无关。
!\[03_云原生/云原生技术栈/Kubernetes/image/9128b9bd47d25c19bfbc434753023c63_MD5.jpg]
!\[03_云原生/云原生技术栈/Kubernetes/image/9e27267ef0b5fadad09cb1dbe35a8354_MD5.jpg]
六、worker 节点使用 kubectl 管理集群
1. 现象
使用 kubeadm 安装的集群,如果直接在 node 节点执行 kubectl,会报错:
text
E0707 16:22:28.641735 125586 memcache.go:265] couldn't get current server API group list:
Get "http://localhost:8080/api?timeout=32s": dial tcp [::1]:8080: connect: connection refused
The connection to the server localhost:8080 was refused - did you specify the right host or port?
(同样的报错会重复出现多次。)
2. 原因
kubectl 默认读取 ~/.kube/config;找不到这个文件时,会退回到 localhost:8080。worker 节点上不运行 kube-apiserver,所以连接被拒绝。
因此 node 节点要使用 kubectl,需要一份指向 apiserver 地址、并带有客户端证书的 kubeconfig。
3. 解决
只要把 master 上的 /etc/kubernetes/admin.conf 复制到 node 节点的 $HOME/.kube/config,node 节点就可以使用 kubectl 管理集群。
步骤 1:在 node 节点创建 .kube 目录
bash
mkdir /root/.kube
步骤 2:在 master 上复制 admin.conf
bash
scp /etc/kubernetes/admin.conf node1:/root/.kube/config
首次连接需要确认主机指纹:
text
The authenticity of host 'node1 (192.168.100.128)' can't be established.
ECDSA key fingerprint is SHA256:e5mRTl+WlA20Zn03z1WL+/cG8/uXbSM9qHk9LFHjA.
ECDSA key fingerprint is MD5:17:87:19:d0:af:de:2a:62:a1:97:b7:9c:a7:c4:8b:9f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'node1,192.168.100.128' (ECDSA) to the list of known hosts.
root@node1's password: # 输入 node1 的 root 密码
admin.conf
步骤 3:在 node 节点验证
bash
kubectl get nodes
能正常输出节点列表即配置成功。
⚠️
admin.conf内含集群管理员证书,权限很高。生产环境不建议直接分发,最好为运维人员单独签发受限的 kubeconfig。