Kubernetes 资源管理总结
Kubernetes 资源管理总结
一、资源管理核心概念
Kubernetes 中所有内容均抽象为资源,管理 Kubernetes 本质是对各类资源进行操作,核心资源及作用如下:
| 资源类别 | 核心资源 | 关键作用 | 
|---|---|---|
| 基础管理单元 | Pod | 最小管理单元,容器必须部署在 Pod 内,K8s 通常不直接管理 Pod | 
| Pod 管理工具 | Pod 控制器(ReplicationController/RC、ReplicaSet/RS、Deployment/deploy 等) | 间接管理 Pod,实现 Pod 的创建、扩容、缩容、自愈等功能 | 
| 服务访问 | Service | 提供 Pod 服务的访问入口,实现 Pod 对外暴露服务 | 
| 数据存储 | 存储系统(Volume、PersistentVolume/PV、PersistentVolumeClaim/PVC 等) | 实现 Pod 中程序数据的持久化存储 | 
| 资源隔离 | Namespace | 用于隔离 Pod 等资源,不同 Namespace 下资源名称可重复 | 
| 配置管理 | ConfigMap(cm)、Secret | 存储应用配置信息,Secret 用于存储敏感配置 | 
二、三种资源管理方式
Kubernetes 提供三种资源管理方式,各有适用场景及优缺点,具体对比如下:
| 管理方式 | 核心操作 | 适用场景 | 优点 | 缺点 | 推荐用法 | 
|---|---|---|---|---|---|
| 命令式对象管理 | 直接用 kubectl命令操作资源(如kubectl runkubectl get) | 测试环境 | 操作简单、直接 | 仅能操作活动对象,无法审计和跟踪操作记录 | 查询资源( kubectl get/describe 资源名) | 
| 命令式对象配置 | 通过 kubectl create/patch/delete -f 配置文件,结合 YAML 配置文件操作 | 开发环境 | 可通过配置文件审计、跟踪操作 | 项目规模大时,配置文件数量多,管理和操作繁琐 | 删除资源( kubectl delete -f XXX.yaml) | 
| 声明式对象配置 | 仅通过 kubectl apply -f 配置文件操作 | 开发环境 | 支持目录级操作,可定义资源最终状态 | 意外故障时,问题定位和调试难度较高 | 创建 / 更新资源( kubectl apply -f XXX.yaml) | 
1. 命令式对象管理
- 
核心工具: kubectl(K8s 集群命令行工具,可管理集群及部署容器化应用)
- 
命令语法: kubectl [command] [type] [name] [flags]- command:资源操作(如 create 创建、get 获取、delete 删除、edit 编辑等)
- type:资源类型(如 pod、deployment、service 等,可通过- kubectl api-resources查看所有资源)
- name:资源名称(大小写敏感)
- flags:额外可选参数(如- -o yaml以 YAML 格式展示结果)
 
- 
常用操作示例: - 查看所有 Pod:kubectl get pods
- 查看指定 Pod(YAML 格式):kubectl get pod pod_name -o yaml
- 创建 Namespace:kubectl create namespace cy
- 在指定 Namespace 创建 Pod:kubectl run pod1 --image=nginx -n cy
- 删除 Pod/Namespace:kubectl delete pod pod-xxxxxx/kubectl delete ns cy
 
- 查看所有 Pod:
2. 命令式对象配置
- 核心逻辑:命令 + YAML配置文件(配置文件中定义资源参数)
- 操作流程示例:
- 编写 YAML 配置文件(如nginxpod.yaml),可同时定义多个资源(如 Namespace+Pod)
- 创建资源:kubectl create -f nginxpod.yaml
- 查看资源:kubectl get -f nginxpod.yaml(仅查看该配置文件定义的资源)
- 删除资源:kubectl delete -f nginxpod.yaml(同时删除配置文件中所有资源)
 
- 编写 YAML 配置文件(如
3. 声明式对象配置
- 核心逻辑:通过kubectl apply -f 配置文件定义资源最终状态,K8s 自动匹配状态执行操作
- 核心特性:
- 资源不存在时,自动创建(等效于kubectl create)
- 资源已存在时,对比当前状态与配置文件状态,仅更新差异部分(等效于kubectl patch)
 
- 资源不存在时,自动创建(等效于
- 操作示例:
- 首次执行:kubectl apply -f nginxpod.yaml(创建资源)
- 再次执行:kubectl apply -f nginxpod.yaml(无变动则提示 “资源未修改”)
 
- 首次执行:
三、关键补充说明
1. kubectl 节点运行配置
- 
默认仅 Master 节点配置 kubectl,若需在 Node 节点运行,需将 Master 节点的 $HOME/.kube配置目录复制到 Node 节点: - 在 Master 节点执行:scp -r $HOME/.kube node1:$HOME/(node1 为目标 Node 节点名称)
 
- 在 Master 节点执行:
2. 资源分类与常用缩写
| 资源分类 | 资源名称 | 缩写 | 
|---|---|---|
| 集群资源 | nodes | no | 
| 资源隔离 | namespaces | ns | 
| 基础单元 | pods | po | 
| Pod 控制器 | deployment | deploy | 
| Pod 控制器 | replicasets | rs | 
| Pod 控制器 | cronjobs | cj | 
| Pod 控制器 | statefulsets | sts | 
| 服务访问 | services | svc | 
| 服务访问 | ingress | ing | 
| 配置管理 | configmaps | cm | 
具体示例:
使用 Kubernetes 命令行工具 kubectl 查看当前 Kubernetes 集群中的所有节点(nodes)信息
执行后会显示集群中节点的基本状态,包括节点名称、是否就绪(Ready)、角色、年龄(运行时长)、 Kubernetes 版本等信息
[root@node1 ~]# kubectl get nodes
NAME                STATUS   ROLES           AGE   VERSION
master              Ready    control-plane   38h   v1.28.15
node1.exmaple.com   Ready    <none>          38h   v1.28.15
node2.example.com   Ready    <none>          38h   v1.28.15
(表示集群中有两个节点,均处于就绪状态)
使用 Kubernetes 命令行工具 kubectl 查看其帮助信息:
[root@node1 ~]# kubectl --help
kubectl 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 stdinexpose          Take a replication controller, service, deployment or pod and expose it as a new Kubernetes servicerun             Run a particular image on the clusterset             Set specific features on objectsBasic Commands (Intermediate):explain         Get documentation for a resourceget             Display one or many resourcesedit            Edit a resource on the serverdelete          Delete resources by file names, stdin, resources and names, or by resources and label selectorDeploy Commands:rollout         Manage the rollout of a resourcescale           Set a new size for a deployment, replica set, or replication controllerautoscale       Auto-scale a deployment, replica set, stateful set, or replication controllerCluster Management Commands:certificate     Modify certificate resourcescluster-info    Display cluster informationtop             Display resource (CPU/memory) usagecordon          Mark node as unschedulableuncordon        Mark node as schedulabledrain           Drain node in preparation for maintenancetaint           Update the taints on one or more nodesTroubleshooting and Debugging Commands:describe        Show details of a specific resource or group of resourceslogs            Print the logs for a container in a podattach          Attach to a running containerexec            Execute a command in a containerport-forward    Forward one or more local ports to a podproxy           Run a proxy to the Kubernetes API servercp              Copy files and directories to and from containersauth            Inspect authorizationdebug           Create debugging sessions for troubleshooting workloads and nodesevents          List eventsAdvanced Commands:diff            Diff the live version against a would-be applied versionapply           Apply a configuration to a resource by file name or stdinpatch           Update fields of a resourcereplace         Replace a resource by file name or stdinwait            Experimental: Wait for a specific condition on one or many resourceskustomize       Build a kustomization target from a directory or URLSettings Commands:label           Update the labels on a resourceannotate        Update the annotations on a resourcecompletion      Output shell completion code for the specified shell (bash, zsh, fish, or powershell)Other Commands:api-resources   Print the supported API resources on the serverapi-versions    Print the supported API versions on the server, in the form of "group/version"config          Modify kubeconfig filesplugin          Provides utilities for interacting with pluginsversion         Print the client and server version informationUsage: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).
使用 Kubernetes 命令行工具 kubectl 查看当前 Kubernetes 集群中的所有命名空间(namespace)信息
执行后会显示集群中命名空间的基本状态,包括命名空间名称、状态(通常为 Active)、创建时间等信息。命名空间用于在集群中划分资源,实现资源隔离和管理:
[root@node1 ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   38h
kube-node-lease   Active   38h
kube-public       Active   38h
kube-system       Active   38h
[root@node1 ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   39h
kube-node-lease   Active   39h
kube-public       Active   39h
kube-system       Active   39h
(表示集群中默认存在的几个命名空间)
使用 Kubernetes 命令行工具 kubectl 查看 kube-system 命名空间下的所有 Pod 信息
其中,-n kube-system 是指定命名空间的参数,kube-system 是 Kubernetes 集群的系统命名空间,通常用于运行集群核心组件(如 kube-apiserver、kube-controller-manager、kube-proxy 等)相关的 Pod
执行后会显示该命名空间下 Pod 的名称、状态、重启次数、运行时长等信息,帮助用户了解集群系统组件的运行状态:
[root@node1 ~]# kubectl get pods -n kube-system 
NAME                                      READY   STATUS    RESTARTS      AGE
calico-kube-controllers-9d57d8f49-xp62k   1/1     Running   1 (47m ago)   38h
calico-node-5b5dz                         1/1     Running   1 (47m ago)   38h
calico-node-c5nkj                         1/1     Running   1 (47m ago)   38h
calico-node-nkl7z                         1/1     Running   1 (47m ago)   38h
coredns-6554b8b87f-h6265                  1/1     Running   1 (47m ago)   39h
coredns-6554b8b87f-p4vrt                  1/1     Running   1 (47m ago)   39h
etcd-master                               1/1     Running   1 (47m ago)   39h
kube-apiserver-master                     1/1     Running   1 (47m ago)   39h
kube-controller-manager-master            1/1     Running   1 (47m ago)   39h
kube-proxy-62dkk                          1/1     Running   1 (47m ago)   39h
kube-proxy-tjfkz                          1/1     Running   1 (47m ago)   38h
kube-proxy-wddnk                          1/1     Running   1 (47m ago)   38h
kube-scheduler-master                     1/1     Running   1 (47m ago)   39h
使用 Kubernetes 命令行工具 kubectl 查看 kube-system 命名空间下名为 calico-node-5b5dz 的 Pod 的详细描述信息
其中:
- describe pod用于获取某个 Pod 的详细信息(包括状态、事件、容器配置、挂载的卷、网络信息等)
- calico-node-5b5dz是具体的 Pod 名称(通常是 Calico 网络插件的节点组件 Pod)
- -n kube-system指定该 Pod 所在的命名空间为- kube-system(系统命名空间)
执行后会输出该 Pod 的详细运行状态、事件日志(如启动过程中的警告或错误)、容器参数、资源限制等信息,常用于排查 Pod 运行异常(如启动失败、状态异常等)的问题:
[root@node1 ~]# kubectl describe pod calico-node-5b5dz -n kube-system 
Name:                 calico-node-5b5dz
Namespace:            kube-system
Priority:             2000001000
Priority Class Name:  system-node-critical
Service Account:      calico-node
Node:                 node1.exmaple.com/192.168.100.20
Start Time:           Tue, 28 Oct 2025 19:20:10 +0800
Labels:               controller-revision-hash=747b558599k8s-app=calico-nodepod-template-generation=1
Annotations:          <none>
Status:               Running
IP:                   192.168.100.20
IPs:IP:           192.168.100.20
Controlled By:  DaemonSet/calico-node
Init Containers:
........
使用 Kubernetes 命令行工具 kubectl 在集群中创建一个名为 nginx-port 的 Pod,该 Pod 基于 nginx:latest 镜像运行,并指定容器暴露的端口为 80
其中:
- run是创建 Pod 或 Deployment 的命令(在较新的 Kubernetes 版本中,默认会创建 Deployment 来管理 Pod)
- nginx-port是创建的资源(Pod/Deployment)的名称
- --image=nginx:latest指定使用最新版本的 Nginx 镜像
- --port=80声明容器要暴露的端口为 80(Nginx 默认的 HTTP 服务端口)
执行后,集群会拉取指定的 Nginx 镜像并启动容器,可通过 kubectl get pods 查看该 Pod 的运行状态:
[root@master ~]# kubectl run nginx-port --image=nginx:latest --port=80
pod/nginx-port created
使用 Kubernetes 命令行工具 kubectl 查看当前命名空间(默认是 default 命名空间)下的所有 Pod 信息
执行后会显示该命名空间中 Pod 的基本状态,包括 Pod 名称、就绪状态(如 1/1 表示容器正常运行)、状态(如 Running 表示运行中)、重启次数、运行时长等信息,帮助用户快速了解当前命名空间内 Pod 的运行情况
[root@master ~]# kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
nginx-port   1/1     Running   0          108s
(表示 default 命名空间中有一个名为 nginx-port 的 Pod,处于运行状态)
使用 Kubernetes 命令行工具 kubectl,查看当前默认命名空间(通常为 default)中名为 nginx-port 的 Pod 的详细信息
执行后会输出该 Pod 的全面细节,包括但不限于:
- Pod 的基本状态(如就绪情况、IP 地址、所在节点)
- 容器的配置(使用的镜像、启动参数、暴露的端口、资源限制等)
- 事件记录(如 Pod 被调度到哪个节点、容器启动过程中的日志、可能出现的错误或警告信息)
- 挂载的存储卷、网络配置等
[root@master ~]# kubectl describe pod nginx-port 
Name:             nginx-port
Namespace:        default
Priority:         0
Service Account:  default
Node:             node2.example.com/192.168.100.30
Start Time:       Thu, 30 Oct 2025 10:07:38 +0800
Labels:           run=nginx-port
Annotations:      cni.projectcalico.org/containerID: 7ccb51e9fecf63ea27e3e246ed64bac6b3949ada1beac0493e864eed8ec65714cni.projectcalico.org/podIP: 172.16.221.1/32cni.projectcalico.org/podIPs: 172.16.221.1/32
Status:           Running
IP:               172.16.221.1
IPs:IP:  172.16.221.1
Containers:nginx-port:Container ID:   docker://85c7b06b0227af69a7b70cf3c7bcd6edc6c0cd7749eaa5bec664765a562e75daImage:          nginx:latestImage ID:       docker-pullable://nginx@sha256:f547e3d0d5d02f7009737b284abc87d808e4252b42dceea361811e9fc606287fPort:           80/TCPHost Port:      0/TCPState:          RunningStarted:      Thu, 30 Oct 2025 10:07:51 +0800Ready:          TrueRestart Count:  0Environment:    <none>Mounts:/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-rf42w (ro)
Conditions:Type              StatusInitialized       True Ready             True ContainersReady   True PodScheduled      True 
Volumes:kube-api-access-rf42w:Type:                    Projected (a volume that contains injected data from multiple sources)TokenExpirationSeconds:  3607ConfigMapName:           kube-root-ca.crtConfigMapOptional:       <nil>DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300snode.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:Type    Reason     Age    From               Message----    ------     ----   ----               -------Normal  Scheduled  5m28s  default-scheduler  Successfully assigned default/nginx-port to node2.example.comNormal  Pulling    5m27s  kubelet            Pulling image "nginx:latest"Normal  Pulled     5m15s  kubelet            Successfully pulled image "nginx:latest" in 12.376s (12.376s including waiting)Normal  Created    5m15s  kubelet            Created container nginx-portNormal  Started    5m15s  kubelet            Started container nginx-port
该命令主要用于排查 Pod 运行中的问题(比如启动失败、状态异常等),通过详细信息可快速定位故障原因
使用 Kubernetes 命令行工具 kubectl 查看当前命名空间(默认是 default 命名空间)下所有 Pod 的详细信息,并以 YAML 格式输出
其中,-o yaml 是指定输出格式为 YAML(一种结构化的数据格式,便于查看和编辑资源的完整配置)
执行后会展示每个 Pod 的完整定义和状态信息,包括元数据(名称、命名空间、标签等)、规格(容器配置、镜像、端口、资源限制、重启策略等)、状态(运行节点、IP 地址、容器状态、事件等)
[root@master ~]# kubectl get pods -o yaml
.....
该命令常用于查看 Pod 的完整配置细节,或导出配置用于备份、编辑后重新创建资源等场景。由于输出内容较详细,通常会结合管道命令(如 | less)分页查看
使用 Kubernetes 命令行工具 kubectl 查看当前命名空间(默认是 default 命名空间)中名为 nginx-port 的单个 Pod 的完整信息,并以 YAML 格式输出
其中:
- get pod nginx-port明确指定获取名为- nginx-port的 Pod 的信息
- -o yaml指定输出格式为 YAML(一种结构化格式,包含资源的完整配置和状态细节)
执行后会展示该 Pod 的全部定义,包括元数据(名称、命名空间、标签等)、规格(容器镜像、端口、资源配置、重启策略等)、状态(运行节点、IP 地址、容器状态、事件等)
[root@master ~]# kubectl get pod nginx-port -o yaml
....
该命令常用于深入查看某个特定 Pod 的完整配置细节,或导出其 YAML 配置用于备份、修改后重新部署等场景。由于内容较详细,通常会搭配 | less 等命令分页查看
使用 Kubernetes 命令行工具 kubectl 查看当前 Kubernetes 集群中所有可用的 API 资源(即 Kubernetes 支持的各类资源对象)
执行后会列出集群中所有可操作的资源类型,包括资源名称、简称(别名)、API 组、是否命名空间隔离、资源_kind(资源类型标识)等信息
[root@master ~]# kubectl api-resources 
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
selfsubjectreviews                             authentication.k8s.io/v1               false        SelfSubjectReview
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v2                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1                               true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
bgpconfigurations                              crd.projectcalico.org/v1               false        BGPConfiguration
bgppeers                                       crd.projectcalico.org/v1               false        BGPPeer
blockaffinities                                crd.projectcalico.org/v1               false        BlockAffinity
caliconodestatuses                             crd.projectcalico.org/v1               false        CalicoNodeStatus
clusterinformations                            crd.projectcalico.org/v1               false        ClusterInformation
felixconfigurations                            crd.projectcalico.org/v1               false        FelixConfiguration
globalnetworkpolicies                          crd.projectcalico.org/v1               false        GlobalNetworkPolicy
globalnetworksets                              crd.projectcalico.org/v1               false        GlobalNetworkSet
hostendpoints                                  crd.projectcalico.org/v1               false        HostEndpoint
ipamblocks                                     crd.projectcalico.org/v1               false        IPAMBlock
ipamconfigs                                    crd.projectcalico.org/v1               false        IPAMConfig
ipamhandles                                    crd.projectcalico.org/v1               false        IPAMHandle
ippools                                        crd.projectcalico.org/v1               false        IPPool
ipreservations                                 crd.projectcalico.org/v1               false        IPReservation
kubecontrollersconfigurations                  crd.projectcalico.org/v1               false        KubeControllersConfiguration
networkpolicies                                crd.projectcalico.org/v1               true         NetworkPolicy
networksets                                    crd.projectcalico.org/v1               true         NetworkSet
endpointslices                                 discovery.k8s.io/v1                    true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta3   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta3   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1                              true         PodDisruptionBudget
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
csistoragecapacities                           storage.k8s.io/v1                      true         CSIStorageCapacity
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment
例如,常见的资源包括 pods(简称 po)、services(简称 svc)、deployments(简称 deploy)、namespaces(简称 ns)等
该命令帮助用户了解集群支持的资源类型,方便在使用 kubectl 操作时快速查询资源名称或简称(例如知道 deploy 是 deployments 的简称后,可使用 kubectl get deploy 简化命令)
使用 Kubernetes 命令行工具 kubectl 查看 pod 资源的详细说明文档,包括其配置结构、各字段的含义和用法
执行后会输出 pod 资源的层级结构说明,涵盖 pod 的元数据(metadata)、规格(spec)、状态(status)等主要部分,以及每个部分下的具体字段(如 metadata.name、spec.containers 等)的解释
[root@master ~]# kubectl explain pod
KIND:       Pod
VERSION:    v1DESCRIPTION:Pod is a collection of containers that can run on a host. This resource iscreated by clients and scheduled onto hosts.FIELDS:apiVersion	<string>APIVersion defines the versioned schema of this representation of an object.Servers should convert recognized schemas to the latest internal value, andmay reject unrecognized values. More info:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resourceskind	<string>Kind is a string value representing the REST resource this objectrepresents. Servers may infer this from the endpoint the client submitsrequests to. Cannot be updated. In CamelCase. More info:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kindsmetadata	<ObjectMeta>Standard object's metadata. More info:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadataspec	<PodSpec>Specification of the desired behavior of the pod. More info:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-statusstatus	<PodStatus>Most recently observed status of the pod. This data may not be up to date.Populated by the system. Read-only. More info:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
例如,会说明 spec.containers 用于定义 Pod 中的容器列表,spec.restartPolicy 用于指定容器重启策略等
该命令常用于编写或调试 Pod 的 YAML/JSON 配置文件时,帮助用户理解每个配置字段的含义和合法值,确保配置符合 Kubernetes API 的要求。如果需要更深入查看某个子字段(如 pod.spec.containers),可以使用 kubectl explain pod.spec.containers 进一步查询
使用 Kubernetes 命令行工具 kubectl 查看当前命名空间(默认是 default 命名空间)中名为 nginx-port 的 Pod 的日志输出
执行后会显示该 Pod 中主容器(如果 Pod 只有一个容器)的运行日志,内容通常包括应用程序的启动信息、运行过程中的输出、错误提示等(对于 Nginx 来说,可能会包含访问日志、启动过程日志等)
[root@master ~]# kubectl logs nginx-port 
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2025/10/30 02:07:51 [notice] 1#1: using the "epoll" event method
2025/10/30 02:07:51 [notice] 1#1: nginx/1.29.3
2025/10/30 02:07:51 [notice] 1#1: built by gcc 14.2.0 (Debian 14.2.0-19) 
2025/10/30 02:07:51 [notice] 1#1: OS: Linux 5.14.0-427.13.1.el9_4.x86_64
2025/10/30 02:07:51 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1073741816:1073741816
2025/10/30 02:07:51 [notice] 1#1: start worker processes
2025/10/30 02:07:51 [notice] 1#1: start worker process 29
2025/10/30 02:07:51 [notice] 1#1: start worker process 30
如果 Pod 包含多个容器,需要通过 -c <容器名> 指定具体容器,例如 kubectl logs nginx-port -c <容器名称>,该命令主要用于排查 Pod 中应用的运行问题,通过日志了解程序的执行状态或错误原因
使用 Kubernetes 命令行工具 kubectl 在集群中创建一个名为 sy 的命名空间(namespace)
命名空间是 Kubernetes 中用于隔离资源的逻辑分区,可将不同的应用、环境(如开发、测试、生产)或团队的资源划分到不同命名空间中,避免名称冲突并便于管理
执行后,集群中会新增一个 sy 命名空间,后续可通过 -n sy 参数指定将资源(如 Pod、Service 等)部署到该命名空间中。例如:kubectl run test -n sy --image=nginx 会在 sy 命名空间创建一个 Nginx Pod:
[root@master ~]# kubectl create namespace sy
namespace/sy created
可通过 kubectl get namespaces 查看是否创建成功:
[root@master ~]# kubectl get namespaces 
NAME              STATUS   AGE
default           Active   40h
kube-node-lease   Active   40h
kube-public       Active   40h
kube-system       Active   40h
sy                Active   110s
使用 Kubernetes 命令行工具 kubectl 在 sy 命名空间中创建一个名为 pod1 的 Pod,该 Pod 基于 nginx 镜像运行
其中:
- run pod1表示创建一个名为- pod1的资源(在较新的 Kubernetes 版本中,默认会创建 Deployment 来管理该 Pod)
- --image=nginx指定使用- nginx镜像(默认拉取最新版本)
- -n sy明确指定该资源创建在- sy命名空间下(而非默认的- default命名空间)
执行后,集群会在 sy 命名空间中拉取 Nginx 镜像并启动相关容器,可通过 kubectl get pods -n sy 查看该 Pod 的运行状态:
[root@master ~]# kubectl run pod1 --image=nginx -n sy
pod/pod1 created
[root@master ~]# kubectl get pods -n sy
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          78s
kubectl子命令tab补齐:
[root@master ~]# source /usr/share/bash-completion/bash_completion
[root@master ~]# source <(kubectl completion bash)
[root@master ~]# echo "source <(kubectl completion bash)" >> ~/.bashrc
使用 Kubernetes 命令行工具 kubectl 编辑 sy 命名空间下名为 pod1 的 Pod 的配置信息
执行后,会打开系统默认的文本编辑器(如 vi),显示该 Pod 的完整 YAML 配置(包括元数据、规格、状态等)。用户可以在编辑器中修改配置(例如调整容器镜像版本、资源限制、环境变量等),保存退出后,Kubernetes 会尝试应用这些修改
[root@master ~]# kubectl edit pod pod1 -n sy
Edit cancelled, no changes made.
需要注意的是,Pod 有一些字段在创建后是不可修改的(如名称、命名空间等),修改这些字段会导致更新失败。如果需要修改不可变字段,通常需要删除原 Pod 后重新创建
该命令常用于临时调整 Pod 的可配置参数,快速更新 Pod 的运行配置
使用 Kubernetes 命令行工具 kubectl 删除 sy 命名空间下名为 pod1 的 Pod
执行后,Kubernetes 会终止该 Pod 中的容器,并从集群中移除该 Pod 资源。如果该 Pod 是由 Deployment、StatefulSet 等控制器管理的,控制器可能会自动重新创建一个新的 Pod 以维持期望的副本数;如果是独立的 Pod(未被控制器管理),则会被彻底删除:
[root@master ~]# kubectl delete pod pod1 -n sy
pod "pod1" deleted
可通过 kubectl get pods -n sy 确认该 Pod 是否已被删除。该命令常用于清理不再需要的 Pod 资源,或在 Pod 异常时删除后重新创建:
[root@master ~]# kubectl get pods -n sy
No resources found in sy namespace.
使用 Kubernetes 命令行工具 kubectl 删除名为 sy 的命名空间(namespace)
执行后,Kubernetes 会删除 sy 命名空间及其内部的所有资源(包括 Pod、Service、Deployment 等)。删除过程是级联的,即先删除命名空间内的所有资源,再删除命名空间本身:
[root@master ~]# kubectl delete ns sy
namespace "sy" deleted
需要注意:
- 此操作不可逆,删除后命名空间及内部资源会被彻底清除,无法直接恢复
- 如果命名空间内有资源删除失败(如资源被锁定或依赖未解除),命名空间可能会处于 Terminating状态,需要排查并手动清理残留资源后才能完成删除
可通过 kubectl get ns 确认 sy 命名空间是否已被删除。该命令常用于清理不再需要的命名空间及其中的所有资源:
[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   43h
kube-node-lease   Active   43h
kube-public       Active   43h
kube-system       Active   43h
创建一个nginxpod.yaml,内容如下:
Kubernetes Pod 的 YAML 配置清单,用于定义一个基于 Nginx 的 Pod
配置清单的各部分含义:
[root@master ~]# vim nginxpod.yaml
apiVersion: v1      //指定使用的 Kubernetes API 版本(v1 是核心 API 版本)
kind: Pod           //声明资源类型为 Pod
metadata:           //元数据,其中 name: nginx 定义了 Pod 的名称为 nginxname: nginx
spec:               //Pod 的规格配置:containers:       //定义 Pod 中的容器列表(此处只有一个容器)- name: nginx     //容器名称为 nginximage: nginx:latest       //容器使用的镜像是最新版本的 Nginxports:          //容器暴露的端口,containerPort: 80 表示容器内部监听 80 端口(Nginx 默认的 HTTP 服务端口)- containerPort: 80
~ 
使用 Kubernetes 命令行工具 kubectl,根据 nginxpod.yaml 文件中定义的配置,在集群中创建对应的资源
其中:
- create是创建资源的命令
- -f nginxpod.yaml指定从名为- nginxpod.yaml的文件中读取资源配置(- -f表示 “从文件读取”)
结合前面的 nginxpod.yaml 内容,该命令会基于文件中定义的配置,在 Kubernetes 集群中创建一个名为 nginx 的 Pod,该 Pod 使用 nginx:latest 镜像,容器内部暴露 80 端口
执行成功后,可通过 kubectl get pods 查看该 Pod 的运行状态。如果后续需要更新该资源,通常会使用 kubectl apply -f nginxpod.yaml(apply 支持创建和更新,而 create 仅用于首次创建):
[root@master ~]# kubectl create -f nginxpod.yaml 
pod/nginx created
[root@master ~]# kubectl get -f nginxpod.yaml 
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          5m57s
[root@master ~]# kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
nginx        1/1     Running   0          11m
nginx-pod    1/1     Running   0          5h36m
nginx-port   1/1     Running   0          5h6m
使用 Kubernetes 命令行工具 kubectl,根据 nginxpod.yaml 文件中定义的资源配置,删除集群中对应的资源
其中:
- delete是删除资源的命令
- -f nginxpod.yaml指定从- nginxpod.yaml文件中读取要删除的资源信息(文件中定义的是名为- nginx的 Pod)
执行后,Kubernetes 会删除该 YAML 文件中声明的 Pod(即名为 nginx 的 Pod)。删除效果与 kubectl delete pod nginx 一致,但通过配置文件删除的方式更便捷(无需手动输入资源名称,尤其适用于复杂资源或批量操作)
[root@master ~]# kubectl delete -f nginxpod.yaml 
pod "nginx" deleted
可通过 kubectl get pods 确认该 Pod 是否已被删除:
[root@master ~]# kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
nginx-pod    1/1     Running   0          5h46m
nginx-port   1/1     Running   0          5h15m
使用 Kubernetes 命令行工具 kubectl,根据 nginxpod.yaml 文件中的配置,在集群中创建或更新对应的资源(此处为 Pod)
其中:
- apply是 Kubernetes 中用于创建或更新资源的核心命令,它会对比文件中定义的期望状态与集群中资源的当前状态,自动执行创建(若资源不存在)或更新(若资源已存在且配置有变化)操作
- -f nginxpod.yaml指定从- nginxpod.yaml文件读取资源配置
结合前面的 nginxpod.yaml 内容,该命令会根据文件中定义的配置:
- 若集群中尚无名为 nginx的 Pod,则创建该 Pod
- 若该 Pod 已存在且配置与文件不一致(如镜像版本、端口等有修改),则更新 Pod 以匹配文件中的配置(注:Pod 的部分字段不可更新,此时可能需要先删除旧 Pod 再重新创建)
[root@master ~]# kubectl apply -f nginxpod.yaml 
pod/nginx created
[root@master ~]# kubectl get -f nginxpod.yaml 
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          5m27s
apply 命令相比 create 更适合持续管理资源,支持通过配置文件维护资源的完整生命周期,是实际使用中更推荐的方式。执行后可通过 kubectl get pods 查看资源状态:
## 创建命名空间配置文件 ns.yaml
通过 vim 编辑 ns.yaml,定义了一个名为 shenyi 的命名空间(Namespace),配置中指定了 apiVersion: v1(核心 API 版本)、资源类型 kind: Namespace 及元数据 metadata.name: shenyi[root@master ~]# vim ns.yaml
apiVersion: v1
kind: Namespace
metadata:name: shenyi
~  ## 应用命名空间配置
执行 kubectl apply -f ns.yaml,Kubernetes 根据配置文件创建 shenyi 命名空间,输出 namespace/shenyi created 表示创建成功[root@master ~]# kubectl apply -f ns.yaml 
namespace/shenyi created## 修改 Pod 配置文件 nginxpod.yaml
编辑 nginxpod.yaml 时,在 metadata 中新增 namespace: shenyi,指定该 Pod 会被部署到 shenyi 命名空间(而非默认的 default 命名空间),其他配置(如镜像、端口)保持不变[root@master ~]# vim nginxpod.yaml 
apiVersion: v1
kind: Pod
metadata:name: nginxnamespace: shenyi
spec:containers:- name: nginximage: nginx:latestports:- containerPort: 80
~  ## 应用 Pod 配置
执行 kubectl apply -f nginxpod.yaml,根据配置在 shenyi 命名空间创建名为 nginx 的 Pod,输出 pod/nginx created 表示创建成功[root@master ~]# kubectl apply -f nginxpod.yaml 
pod/nginx created## 验证 Pod 状态
kubectl get -f nginxpod.yaml:直接通过配置文件查看对应资源(即 shenyi 命名空间的 nginx Pod)的状态,显示其处于运行中(Running)。
kubectl get pods -n shenyi:查看 shenyi 命名空间下的所有 Pod,确认 nginx Pod 正常运行[root@master ~]# kubectl get -f nginxpod.yaml 
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          2m36s
[root@master ~]# kubectl get pods -n shenyi
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          3m10s
## 复制并编辑配置文件 test.yaml
cp nginxpod.yaml test.yaml:复制原有的 nginxpod.yaml 为 test.yaml,作为新的配置文件模板
编辑 test.yaml 时,使用 --- 分隔符定义了两个资源:
命名空间 luoqi:kind: Namespace,metadata.name: luoqi
Pod nginx:指定 namespace: luoqi,即该 Pod 会部署到 luoqi 命名空间,其他配置(镜像、端口)不变[root@master ~]# cp nginxpod.yaml test.yaml
[root@master ~]# vim test.yaml 
apiVersion: v1
kind: Namespace
metadata:name: luoqi
---
apiVersion: v1
kind: Pod
metadata:name: nginxnamespace: luoqi
spec:containers:- name: nginximage: nginx:latestports:- containerPort: 80
~ ## 应用 test.yaml 创建资源
kubectl apply -f test.yaml:根据文件中的配置,Kubernetes 会依次创建命名空间 luoqi 和该命名空间下的 nginx Pod,输出 namespace/luoqi created 和 pod/nginx created 表示成功[root@master ~]# kubectl apply -f test.yaml 
namespace/luoqi created
pod/nginx created## 验证资源创建结果
kubectl get ns:查看命名空间列表,确认 luoqi 已创建(状态 Active)
kubectl get pods -n luoqi:查看 luoqi 命名空间下的 Pod,确认 nginx 正常运行(Running)[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   45h
kube-node-lease   Active   45h
kube-public       Active   45h
kube-system       Active   45h
luoqi             Active   48s
shenyi            Active   30m
[root@master ~]# kubectl get pods -n luoqi
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          74s## 清理资源
kubectl delete -f test.yaml:通过配置文件删除其定义的所有资源(命名空间 luoqi 和 Pod nginx),实现 “一键清理”
kubectl delete -f ns.yaml:删除之前创建的 shenyi 命名空间(及其内的资源)[root@master ~]# kubectl delete -f test.yaml 
namespace "luoqi" deleted
pod "nginx" deleted最终状态验证
kubectl get ns:确认 luoqi 和 shenyi 命名空间已被删除,仅保留默认命名空间(default、kube-system 等)
kubectl get pods -A:查看所有命名空间的 Pod,确认 luoqi 和 shenyi 下的 Pod 已清理,仅剩 default 命名空间和系统命名空间的 Pod
kubectl get pods -o wide:查看 default 命名空间的 Pod 详情,包括 IP 地址、所在节点等信息,确认剩余 Pod 正常运行[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   45h
kube-node-lease   Active   45h
kube-public       Active   45h
kube-system       Active   45h
shenyi            Active   31m
[root@master ~]# kubectl get pods -n shenyi
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          29m
[root@master ~]# kubectl delete -f ns.yaml 
namespace "shenyi" deleted
[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   45h
kube-node-lease   Active   45h
kube-public       Active   45h
kube-system       Active   45h
[root@master ~]# kubectl get pods -A
NAMESPACE     NAME                                      READY   STATUS    RESTARTS       AGE
default       nginx                                     1/1     Running   0              48m
default       nginx-pod                                 1/1     Running   0              6h37m
default       nginx-port                                1/1     Running   0              6h6m
kube-system   calico-kube-controllers-9d57d8f49-xp62k   1/1     Running   1 (7h7m ago)   45h
kube-system   calico-node-5b5dz                         1/1     Running   1 (7h7m ago)   44h
kube-system   calico-node-c5nkj                         1/1     Running   1 (7h7m ago)   44h
kube-system   calico-node-nkl7z                         1/1     Running   1 (7h7m ago)   45h
kube-system   coredns-6554b8b87f-h6265                  1/1     Running   1 (7h7m ago)   45h
kube-system   coredns-6554b8b87f-p4vrt                  1/1     Running   1 (7h7m ago)   45h
kube-system   etcd-master                               1/1     Running   1 (7h7m ago)   45h
kube-system   kube-apiserver-master                     1/1     Running   1 (7h7m ago)   45h
kube-system   kube-controller-manager-master            1/1     Running   1 (7h7m ago)   45h
kube-system   kube-proxy-62dkk                          1/1     Running   1 (7h7m ago)   45h
kube-system   kube-proxy-tjfkz                          1/1     Running   1 (7h7m ago)   44h
kube-system   kube-proxy-wddnk                          1/1     Running   1 (7h7m ago)   44h
kube-system   kube-scheduler-master                     1/1     Running   1 (7h7m ago)   45h
[root@master ~]# kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
nginx        1/1     Running   0          48m
nginx-pod    1/1     Running   0          6h37m
nginx-port   1/1     Running   0          6h7m
[root@master ~]# kubectl get pods -o wide 
NAME         READY   STATUS    RESTARTS   AGE     IP              NODE                NOMINATED NODE   READINESS GATES
nginx        1/1     Running   0          48m     172.16.221.4    node2.example.com   <none>           <none>
nginx-pod    1/1     Running   0          6h37m   172.16.98.129   node1.exmaple.com   <none>           <none>
nginx-port   1/1     Running   0          6h7m    172.16.221.1    node2.example.com   <none>           <none>
