[ root@master ~]# kubectl get namespaces
NAME STATUS AGE
default Active 17h
kube-flannel Active 18h
kube-node-lease Active 18h
kube-public Active 18h
kube-system Active 18h
[ root@master ~]# kubectl get pods
test-56848fd9dc-cxtnp 1/1 Running 0 25m
test-56848fd9dc-9sw95 1/1 Running 0 27m
[ root@master ~]# kubectl -n kube-flannel get pods
NAME READY STATUS RESTARTS AGE
kube-flannel-ds-hc8gt 1/1 Running 1(17h ago) 17h
kube-flannel-ds-rvzng 1/1 Running 1(17h ago) 17h
kube-flannel-ds-s29g5 1/1 Running 1(17h ago) 17h
核心代码逐行解析
复制代码
kubectl api-resources
底层动作:向 API Server 发送请求,获取当前集群支持的所有 API 资源类型
作用:查看集群支持的资源类型和缩写,是学习 Kubernetes 的必备命令
坑:不同 Kubernetes 版本支持的资源类型可能不同,升级集群后需要重新查看
bash
运行
复制代码
kubectl get namespaces
底层动作:获取集群中所有命名空间的列表
作用:查看集群的命名空间划分,是资源隔离的基础
坑:不要在 default 命名空间部署生产服务,应该为每个项目创建独立的命名空间
bash
运行
复制代码
kubectl -n kube-flannel get pods
底层动作:获取 kube-flannel 命名空间下的所有 Pod
作用:查看指定命名空间的资源状态
坑 :如果省略-n参数,默认只查看 default 命名空间的资源
企业级生产应用
在生产环境中,资源类型的正确使用是集群稳定的关键:
使用 Namespace 进行环境隔离(开发、测试、生产)
使用 Deployment 管理无状态服务
使用 StatefulSet 管理有状态服务(数据库、消息队列)
使用 DaemonSet 部署节点级服务(监控、日志收集)
优化空间:
使用 ResourceQuota 限制命名空间的资源使用
使用 LimitRange 限制 Pod 的资源请求和限制
使用 NetworkPolicy 进行 Pod 间的网络隔离
课后防宕机指南
常见错误 1:在 kube-system 命名空间部署业务服务
报错:可能影响系统组件的正常运行
排查思路:将业务服务部署在独立的命名空间中
常见错误 2:忘记指定命名空间,导致资源创建在错误的位置
报错:找不到创建的资源
排查思路 :使用kubectl get pods --all-namespaces查看所有命名空间的资源
kubectl 常见命令操作
原文:
命令分类
命令
翻译
命令作用
基本命令
create
创建
创建一个资源
edit
编辑
编辑一个资源
get
获取
获取一个资源
patch
更新
更新一个资源
delete
删除
删除一个资源
explain
解释
展示资源文档
运行和调试
run
运行
在集群中运行一个指定的镜像
expose
暴露
暴露资源为 Service
describe
描述
显示资源内部信息
logs
日志
输出容器在 pod 中的日志
attach
缠绕
进入运行中的容器
exec
执行
执行容器中的一个命令
cp
复制
在 Pod 内外复制文件
rollout
发布管理
管理资源的发布
scale
规模
扩 (缩) 容 Pod 的数量
autoscale
自动调整
自动调整 Pod 的数量
高级命令
apply
应用
通过文件对资源进行配置
label
标签
更新资源上的标签
其他命令
cluster-info
集群信息
显示集群信息
version
版本
显示当前 Server 和 Client 的版本
原文:
bash复制代码
[root@master~]#vim test.yml
[ root@master ~]# kubectl edit deployments.apps test
编辑内容:
即改即生效
原文:
不知道意思的可以这样:
复制代码
[root@master~]# kubectl explain deployment.spec.replicas
apps
KIND: Deployment
VERSION: v1
FIELD: replicas <integer>
DESCRIPTION: Number of desired pods.This is a pointer to distinguish between explicit
zero and not specified.Defaults to1.
核心代码逐行解析
复制代码
kubectl edit deployments.apps test
底层动作 :
从 API Server 获取 test Deployment 的当前配置
打开默认编辑器(vim)让用户编辑
保存退出后,将修改后的配置提交给 API Server
API Server 验证配置无误后,更新资源状态
作用:实时编辑运行中的资源配置
坑 :
编辑的是内存中的配置,不会更新原始的 YAML 文件
如果配置有语法错误,会保存失败并提示
生产环境不建议直接 edit,应该修改 YAML 文件后 apply
bash
运行
复制代码
kubectl explain deployment.spec.replicas
底层动作:向 API Server 发送请求,获取 Deployment 资源 spec.replicas 字段的文档
作用:查看资源字段的详细说明,是学习 Kubernetes API 的最佳方式
坑:不同 Kubernetes 版本的字段说明可能不同,要使用与集群版本匹配的文档
企业级生产应用
在生产环境中:
kubectl explain是最权威的 API 文档,比任何第三方资料都准确
kubectl edit只能用于紧急排障,正常变更应该通过 GitOps 流程
kubectl rollout用于管理 Deployment 的发布和回滚
优化空间:
使用kubectl explain --recursive查看完整的资源结构
使用kubectl rollout history查看发布历史
使用kubectl rollout undo回滚到上一个版本
课后防宕机指南
常见错误 1:edit 时修改了只读字段
报错 :the object has been modified; please apply your changes to the latest version and try again
[root@k8s-master ~]# kubectl version
Client Version: v1.30.0
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0
#显示集群信息
复制代码
[root@k8s-master ~]# kubectl cluster-info
Kubernetes control plane is running at https://172.25.254.100:6443
CoreDNS is running at https://172.25.254.100:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
[root@k8s-master ~]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
web 3/3 3 3 69m
#查看资源帮助
复制代码
[root@k8s-master ~]# kubectl explain deployment
apps
KIND: Deployment
GROUP: apps
VERSION: v1
DESCRIPTION:
Deployment enables declarative updates for Pods and ReplicaSets.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
kind <string>
Kind is a string value representing the REST resource this object
represents. Servers may infer this from the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
metadata <ObjectMeta>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
spec <DeploymentSpec>
Specification of the desired behavior of the Deployment.
status <DeploymentStatus>
Most recently observed status of the Deployment.
#查看控制器参数帮助
复制代码
[root@k8s-master ~]# kubectl explain deployment.spec
GROUP: apps
KIND: Deployment
VERSION: v1
FIELD: spec <DeploymentSpec>
DESCRIPTION:
Specification of the desired behavior of the Deployment.
DeploymentSpec is the specification of the desired behavior of the Deployment.
FIELDS:
minReadySeconds <integer>
Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)
paused <boolean>
Indicates that the deployment is paused.
progressDeadlineSeconds <integer>
The maximum time in seconds for which a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.
replicas <integer>
Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.
revisionHistoryLimit <integer>
The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.
selector <LabelSelector> -required
Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. It must match the pod template's labels.
strategy <DeploymentStrategy>
The deployment strategy to use to replace existing pods with new ones.
template <PodTemplateSpec> -required
Template describes the pods that will be created. The only allowed template.spec.restartPolicy value is "Always".
#编辑控制器配置
复制代码
[root@k8s-master ~]# kubectl edit deployments.apps web
编辑内容:
yaml
复制代码
spec:
progressDeadlineSeconds: 600
replicas: 2
[root@k8s-master ~]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
web 2/2 2 2 73m
#利用补丁更改控制器配置
复制代码
[root@k8s-master ~]# kubectl patch deployments.apps web -p '{"spec":{"replicas":4}}'
deployment.apps/web patched
[root@k8s-master ~]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
web 4/4 4 4 74m
#删除资源
复制代码
[root@k8s-master ~]# kubectl delete deployments.apps web
deployment.apps "web" deleted
[root@k8s-master ~]# kubectl get deployments.apps
No resources found in default namespace.
[root@k8s-master ~]# kubectl run testpod --image nginx
pod/testpod created
[root@k8s-master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
testpod 1/1 Running 0 7s
#端口暴露
复制代码
[root@k8s-master ~]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 2d14h
[root@k8s-master ~]# kubectl expose pod testpod --port 80 --target-port 80
service/testpod exposed
[root@k8s-master ~]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 2d14h
testpod ClusterIP 10.106.78.42 <none> 80/TCP 18s
[root@k8s-master ~]# curl 10.106.78.42
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
[root@k8s-master ~]# kubectl logs pods/testpod
/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/
2024/08/29 05:37:29 [notice] 1#1: using the "epoll" event method
2024/08/29 05:37:29 [notice] 1#1: nginx/1.27.1
2024/08/29 05:37:29 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14)
2024/08/29 05:37:29 [notice] 1#1: OS: Linux 5.14.0-427.13.1.el9_4.x86_64
2024/08/29 05:37:29 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1073741816:1073741816
2024/08/29 05:37:29 [notice] 1#1: start worker processes
2024/08/29 05:37:29 [notice] 1#1: start worker process 29
10.244.0.0 - - [29/Aug/2024:05:41:11 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.76.1" "-"
10.244.0.0 - - [29/Aug/2024:05:42:51 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.76.1" "-"
#运行交互 pod
复制代码
[root@k8s-master ~]# kubectl run -it testpod --image busybox
If you don't see a command prompt, try pressing enter.
/ #
# ctrl+pq退出不停止pod
#运行非交互 pod
复制代码
[root@k8s-master ~]# kubectl run nginx --image nginx
pod/nginx created
#进入到已经运行的容器,且容器有交互环境
复制代码
[root@k8s-master ~]# kubectl attach pods/testpod -it
If you don't see a command prompt, try pressing enter.
/ #
#在已经运行的 pod 中运行指定命令
复制代码
[root@k8s-master ~]# kubectl exec -it pods/nginx /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@nginx:/#
#复制文件到 pod 中
复制代码
[root@k8s-master ~]# kubectl cp anaconda-ks.cfg nginx:/
[root@k8s-master ~]# kubectl exec -it pods/nginx /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@nginx:/# ls
anaconda-ks.cfg boot docker-entrypoint.d etc lib media opt root sbin
dev home lib64 mnt proc run srv sys usr
bin docker-entrypoint.sh tmp var
#复制 pod 中的文件到本机
复制代码
[root@k8s-master ~]# kubectl cp nginx:/anaconda-ks.cfg anaconda-ks.cfg
tar: Removing leading `/' from member names
核心代码逐行解析
复制代码
kubectl expose pod testpod --port 80 --target-port 80
底层动作 :
创建一个 ClusterIP 类型的 Service
Service 的标签选择器自动设置为 testpod 的标签
kube-proxy 在所有节点上更新 iptables 规则
访问 Service 的 ClusterIP:80 会被转发到 Pod 的 80 端口
作用:为 Pod 提供一个稳定的访问入口
坑 :
--port是 Service 暴露的端口,--target-port是 Pod 监听的端口
如果 Pod 有多个容器,需要指定--container参数
kubectl exec -it pods/nginx -- /bin/bash
底层动作 :
向 API Server 发送 exec 请求
API Server 将请求转发到 Pod 所在节点的 Kubelet
Kubelet 调用容器运行时,在容器中执行 /bin/bash 命令
建立一个双向的 WebSocket 连接,实现交互式终端
作用:进入运行中的容器进行调试
坑 :
必须使用--分隔 Pod 名称和命令,这是新的语法要求
容器中必须有 /bin/bash 或 /bin/sh 才能进入交互式终端
企业级生产应用
在生产环境中:
kubectl logs是排查应用问题的首选工具
kubectl exec只能用于紧急调试,正常情况下不应该进入容器
kubectl cp用于临时复制文件,不应该用于部署应用
优化空间:
使用kubectl logs -f实时查看日志
使用kubectl logs --previous查看上一个容器的日志
使用kubectl exec --执行非交互式命令,避免进入终端
课后防宕机指南
常见错误 1 :exec 时忘记加-it参数
报错:无法进入交互式终端
排查思路 :加上-it参数,-i表示标准输入,-t表示分配终端
常见错误 2:cp 时路径写错
报错 :tar: /path: Cannot stat: No such file or directory
报错 :Deployment.apps "webcluster" is invalid: spec.template.metadata.labels: Invalid value: map[string]string{"app":"new-webcluster"}: selectordoes not match templatelabels`