哪些企业网站比较好,中国住房和城乡建设局官网,我想阻止一个网站要怎么做,制作网站公司选 择乐云seo一、引言#xff1a;从单机编排到集群编排的革命
1.1 容器编排的演进历程
容器技术发展至今#xff0c;已经从单机运行演变为大规模集群编排的时代。让我们回顾这一演进路径#xff1a;
容器技术演进 {2000年代: chroot - LXC - 进程隔离技术从单机编排到集群编排的革命1.1 容器编排的演进历程容器技术发展至今已经从单机运行演变为大规模集群编排的时代。让我们回顾这一演进路径容器技术演进{2000年代:chroot - LXC - 进程隔离技术,2013年:Docker诞生容器标准化,2014年:Docker Compose解决多容器编排,2015年:Kubernetes v1.0发布谷歌开源,2017年:Kubernetes成为容器编排事实标准,2020年代:云原生生态体系成熟}现实世界的需求变化从运行几个容器到管理成千上万个容器从单机部署到跨多数据中心的多集群管理从手动运维到自动化的弹性伸缩从简单的服务部署到复杂的微服务架构1.2 Kubernetes的诞生背景KubernetesK8s源自谷歌内部的Borg系统谷歌每周运行数十亿个容器积累了15年的容器管理经验。# 谷歌容器管理经验的传承Borg(2003)-Omega(2010)-Kubernetes(2014)# 核心设计哲学# 1. 声明式API描述期望状态系统自动实现# 2. 控制器模式持续监控并调整实际状态# 3. 微服务架构各组件松耦合可独立升级1.3 为什么选择Kubernetes让我们通过一个实际场景对比Docker Compose与Kubernetes# Docker Compose限制单机场景场景问题 1. 单点故障主机宕机服务全部中断 2. 资源限制无法超越单机硬件限制 3. 扩展困难手动管理多实例负载均衡 4. 网络局限跨主机网络配置复杂 5. 存储局限数据卷无法在主机间迁移# Kubernetes解决方案集群场景核心优势 1. 高可用节点故障自动迁移容器 2. 弹性伸缩根据负载自动调整实例数 3. 服务发现自动DNS解析和负载均衡 4. 存储编排支持动态卷供给和迁移 5. 自我修复容器故障自动重启和替换1.4 本章学习目标深入理解Kubernetes的核心架构设计掌握Pod、Deployment、Service三大核心概念能够编写基本的Kubernetes资源配置文件理解Kubernetes的工作机制和调度原理为面试中的Kubernetes问题做好充分准备二、Kubernetes架构深度解析2.1 整体架构概览2.2 控制平面组件详解2.2.1 API Server集群的网关API Server是Kubernetes集群的前端接口所有组件都通过它与集群交互。// API Server的核心功能简化示例typeAPIServerstruct{// 1. 认证AuthenticationAuthenticate(request Request)(UserInfo,error)// 2. 授权AuthorizationAuthorize(user UserInfo,action Action,resource Resource)bool// 3. 准入控制Admission ControlValidate(request Request)(bool,[]AdmissionReview)// 4. 资源操作CRUDCreate(resource Resource)errorGet(resource Resource)(Resource,error)Update(resource Resource)errorDelete(resource Resource)errorList(resources[]Resource)([]Resource,error)// 5. Watch机制实时监控Watch(resource Resource)-chanEvent}// 典型请求流程1.kubectl apply-f deployment.yaml ↓2.kubectl-API Server(REST API over HTTPS)↓3.API Server-认证-授权-准入控制 ↓4.API Server-etcd(存储资源定义)↓5.控制器检测到变化-执行相应操作2.2.2 etcd分布式键值存储etcd是Kubernetes的大脑存储所有集群数据。# etcd的关键特性1. 强一致性基于Raft共识算法2. 高可用支持多节点集群3. 持久化数据持久存储4. 快速读操作线性化写操作在100ms内# 存储的数据类型/registry/pods/default/my-pod# Pod定义/registry/services/default/my-service# Service定义/registry/deployments/default/my-deploy# Deployment定义/registry/nodes/node-1# Node信息/registry/events# 事件记录2.2.3 调度器Scheduler调度器负责将Pod分配到合适的节点上运行。// 调度决策流程简化funcSchedule(pod Pod,nodes[]Node)(Node,error){// 第一步过滤FilteringfeasibleNodes:Filter(pod,nodes)// 过滤条件包括// - 节点资源是否足够CPU、内存// - 节点是否有污点Taint// - Pod是否有节点选择器NodeSelector// - 节点端口冲突检查// - 卷是否可用iflen(feasibleNodes)0{returnnil,errors.New(no suitable nodes)}// 第二步评分Scoringscores:make(map[Node]int)for_,node:rangefeasibleNodes{// 评分策略包括// - 资源平衡倾向于资源使用率低的节点// - 亲和性倾向于特定节点或节点组// - 反亲和性避免在同一节点运行相似Pod// - 节点亲和性根据节点标签评分scores[node]CalculateScore(pod,node)}// 第三步选择SelectingselectedNode:SelectHighestScore(scores)returnselectedNode,nil}2.2.4 控制器管理器Controller Manager控制器管理器运行各种控制器确保集群的当前状态与期望状态一致。// 控制器工作模式调谐循环Reconciliation LoopfuncRunController(){for{// 1. 获取期望状态来自etcddesiredState:GetDesiredStateFromAPI()// 2. 获取当前状态观察集群currentState:ObserveCurrentState()// 3. 比较并采取行动if!CompareStates(desiredState,currentState){// 执行调谐操作Reconcile(desiredState,currentState)}// 4. 等待下一轮检查time.Sleep(SyncPeriod)}}// 内置控制器列表controllers:[]string{Deployment Controller,// 管理DeploymentReplicaSet Controller,// 管理ReplicaSetStatefulSet Controller,// 管理有状态应用DaemonSet Controller,// 每个节点运行一个PodJob Controller,// 管理一次性任务CronJob Controller,// 管理定时任务Node Controller,// 监控节点状态Service Controller,// 管理负载均衡Endpoint Controller,// 维护Service端点Namespace Controller,// 管理命名空间PersistentVolume Controller,// 管理存储卷}2.3 工作节点组件详解2.3.1 Kubelet节点代理Kubelet是运行在每个节点上的主要节点代理负责管理Pod生命周期。// Kubelet的核心职责typeKubeletstruct{// 1. Pod生命周期管理funcCreatePod(podSpec PodSpec)errorfuncStartPod(podIDstring)errorfuncStopPod(podIDstring)errorfuncDeletePod(podIDstring)error// 2. 容器运行时接口CRIruntime ContainerRuntime// Docker, containerd, CRI-O// 3. 容器网络接口CNInetwork NetworkPlugin// Flannel, Calico, Weave// 4. 容器存储接口CSIstorage StoragePlugin// 各种存储驱动// 5. 监控和报告funcReportNodeStatus()NodeStatusfuncReportPodStatus(podIDstring)PodStatus}2.3.2 Kube-Proxy网络代理Kube-Proxy维护节点上的网络规则实现Service的网络抽象。// Kube-Proxy的三种工作模式typeProxyModestringconst(// 1. userspace模式已弃用UserspaceMode ProxyModeuserspace// 2. iptables模式默认IptablesMode ProxyModeiptables// 3. IPVS模式高性能IPVSMode ProxyModeipvs)// IPVS模式的工作原理typeIPVSProxystruct{// 创建虚拟服务funcCreateVirtualService(serviceIPstring,portint)error// 添加真实服务器Pod IPfuncAddRealServer(virtualServicestring,podIPstring,portint)error// 负载均衡算法schedulingAlgorithm:[]string{rr,// 轮询lc,// 最少连接dh,// 目标哈希sh,// 源哈希sed,// 最短预期延迟nq,// 从不排队}}2.3.3 容器运行时Container Runtime容器运行时负责运行容器Kubernetes通过CRI接口与运行时交互。# 支持的容器运行时1. Docker传统通过dockershim2. containerd推荐云原生计算基金会项目3. CRI-O专为Kubernetes设计4. Mirantis Container Runtime原Docker Enterprise# 容器运行时接口CRI标准CRI定义了两个gRPC服务1. RuntimeService: 管理容器生命周期 - RunPodSandbox()# 创建Pod沙箱- CreateContainer()# 创建容器- StartContainer()# 启动容器- StopContainer()# 停止容器2. ImageService: 管理镜像 - PullImage()# 拉取镜像- ListImages()# 列出镜像- RemoveImage()# 删除镜像2.4 插件组件2.4.1 DNS插件CoreDNSCoreDNS为集群提供DNS服务实现服务发现。# CoreDNS配置示例apiVersion:v1kind:ConfigMapmetadata:name:corednsnamespace:kube-systemdata:Corefile:|.:53 { errors # 错误日志 health # 健康检查端点 ready # 就绪检查端点 kubernetes cluster.local in-addr.arpa ip6.arpa { pods verified fallthrough in-addr.arpa ip6.arpa } prometheus :9153 # 监控指标 forward . /etc/resolv.conf # 上游DNS cache 30 # 缓存 loop # 检测循环查询 reload # 自动重载配置 loadbalance # 负载均衡 }2.4.2 网络插件CNI容器网络接口CNI插件负责Pod之间的网络通信。常见CNI插件对比插件网络模型性能特点适用场景FlannelOverlay网络简单易用中小型集群CalicoBGP路由高性能策略丰富生产环境Weave NetOverlay网络加密通信安全要求高的环境CiliumeBPF驱动高性能可观测性大规模集群AWS VPC CNIAWS VPC集成高性能AWS集成AWS EKS三、PodKubernetes的基本构建块3.1 Pod概念深度解析3.1.1 什么是PodPod是Kubernetes中最小的可部署单元但它不是一个容器而是一个或多个容器的组合。# Pod的核心特征apiVersion:v1kind:Podmetadata:name:example-podspec:# Pod级别的配置restartPolicy:Always# 重启策略terminationGracePeriodSeconds:30# 优雅终止宽限期# 共享资源volumes:# 共享存储卷-name:shared-dataemptyDir:{}# 容器定义containers:-name:main-appimage:nginx:1.21volumeMounts:-name:shared-datamountPath:/data# 共享网络命名空间# 所有容器共享同一个IP地址# 容器间可以通过localhost互相访问# 共享UTS命名空间# 所有容器共享相同的主机名# 共享IPC命名空间# 容器间可以通过System V IPC或POSIX消息队列通信3.1.2 为什么需要Pod设计哲学// Pod的设计哲学亲密性容器组typePodstruct{// 容器组共享的特征1.生命周期一致一起创建、一起调度、一起销毁2.资源共享网络、存储、IPC等3.本地通信通过localhost直接通信// 典型使用场景scenarios:[]string{主容器边车容器Sidecar,主容器初始化容器Init Container,主容器适配器容器Adapter,主容器代理容器Proxy,}}// 与传统Docker容器的对比传统Docker方式-每个容器独立运行-容器间通信需要显式配置-生命周期管理复杂 Kubernetes Pod方式-相关容器打包为一个单元-容器间共享网络和存储-统一调度和管理3.2 Pod的生命周期Pod生命周期状态图3.2.1 Pod状态详解typePodPhasestringconst(// Pending: Pod已被系统接受但一个或多个容器尚未创建Pending PodPhasePending// Running: Pod已绑定到节点所有容器已创建Running PodPhaseRunning// Succeeded: Pod中所有容器成功终止不会重启Succeeded PodPhaseSucceeded// Failed: Pod中所有容器已终止至少一个容器失败Failed PodPhaseFailed// Unknown: 无法获取Pod状态Unknown PodPhaseUnknown)typeContainerStatestruct{// 容器可能的状态Waiting*ContainerStateWaiting// 等待启动Running*ContainerStateRunning// 正在运行Terminated*ContainerStateTerminated// 已终止}3.2.2 重启策略RestartPolicyapiVersion:v1kind:Podmetadata:name:restart-policy-demospec:restartPolicy:Always# 可选: Always, OnFailure, Nevercontainers:-name:appimage:busyboxcommand:[sh,-c,sleep 3600]# 重启策略的影响# 1. Always: 容器退出时总是重启默认# 2. OnFailure: 容器异常退出非0状态码时重启# 3. Never: 从不重启容器3.2.3 Pod的创建过程# Pod创建的时间线时间线1. kubectl apply -f pod.yaml ↓2. API Server验证并存储到etcd ↓3. Scheduler检测到未调度的Pod ↓4. Scheduler选择合适的节点 ↓5. Scheduler将节点信息写入Pod ↓6. 目标节点的Kubelet检测到Pod ↓7. Kubelet通过CRI创建Pod沙箱 ↓8. Kubelet创建volume如果需要 ↓9. Kubelet拉取容器镜像 ↓10. Kubelet通过CRI创建容器 ↓11. Kubelet执行容器启动后钩子 ↓12. 容器进入Running状态3.3 Pod配置详解3.3.1 资源请求和限制apiVersion:v1kind:Podmetadata:name:resource-demospec:containers:-name:appimage:nginxresources:# 请求资源调度依据requests:cpu:250m# 250 milliCPU (0.25核心)memory:512Mi# 512 Mebibytesephemeral-storage:2Gi# 临时存储# 限制资源运行限制limits:cpu:500m# 最多使用0.5核心memory:1Gi# 内存硬限制ephemeral-storage:5Ginvidia.com/gpu:1# GPU资源# CPU单位说明# 1 1个CPU核心# 0.5 500m 半个核心# 100m 0.1核心# 内存单位说明# 1Ki 1024 bytes# 1Mi 1024 KiB# 1Gi 1024 MiB3.3.2 健康检查apiVersion:v1kind:Podmetadata:name:health-check-demospec:containers:-name:webimage:nginx# 1. 存活探针Liveness Probe# 检测容器是否正在运行livenessProbe:httpGet:path:/healthzport:8080httpHeaders:-name:Custom-Headervalue:AwesomeinitialDelaySeconds:3# 启动后等待时间periodSeconds:3# 检查间隔timeoutSeconds:1# 超时时间successThreshold:1# 成功阈值failureThreshold:3# 失败阈值# 2. 就绪探针Readiness Probe# 检测容器是否准备好接收流量readinessProbe:exec:command:-cat-/tmp/healthyinitialDelaySeconds:5periodSeconds:5# 3. 启动探针Startup Probe# 检测应用是否已启动K8s 1.16startupProbe:tcpSocket:port:8080failureThreshold:30# 允许长时间启动periodSeconds:10# 探针类型# 1. exec: 执行命令返回0表示成功# 2. httpGet: HTTP GET请求2xx-3xx状态码表示成功# 3. tcpSocket: TCP端口检查连接成功表示成功3.3.3 环境变量和配置apiVersion:v1kind:Podmetadata:name:config-demospec:containers:-name:appimage:nginx# 环境变量配置env:# 1. 直接指定值-name:LOG_LEVELvalue:debug# 2. 从ConfigMap获取-name:DATABASE_HOSTvalueFrom:configMapKeyRef:name:app-configkey:database.hostoptional:true# 可选配置# 3. 从Secret获取-name:API_KEYvalueFrom:secretKeyRef:name:app-secretskey:api-key# 4. 字段引用引用Pod信息-name:MY_NODE_NAMEvalueFrom:fieldRef:fieldPath:spec.nodeName-name:MY_POD_IPvalueFrom:fieldRef:fieldPath:status.podIP-name:MY_POD_NAMESPACEvalueFrom:fieldRef:fieldPath:metadata.namespace# 5. 资源字段引用-name:MY_CPU_REQUESTvalueFrom:resourceFieldRef:containerName:appresource:requests.cpu3.4 多容器Pod模式3.4.1 Sidecar模式apiVersion:v1kind:Podmetadata:name:sidecar-demospec:volumes:-name:shared-logsemptyDir:{}containers:# 主容器Web应用-name:web-appimage:myapp:1.0volumeMounts:-name:shared-logsmountPath:/var/log/appports:-containerPort:8080# 边车容器日志收集器-name:log-collectorimage:fluentd:latestvolumeMounts:-name:shared-logsmountPath:/var/log/app# 共享网络可以直接访问localhost:8080# 共享存储可以读取主容器的日志文件# 边车容器监控代理-name:monitoring-agentimage:prometheus/node-exporterports:-containerPort:91003.4.2 Init Container模式apiVersion:v1kind:Podmetadata:name:init-container-demospec:containers:-name:appimage:myapp:1.0volumeMounts:-name:data-dirmountPath:/data# 初始化容器按顺序执行initContainers:# 1. 等待数据库就绪-name:wait-for-dbimage:busybox:1.28command:[sh,-c,until nslookup mysql-service; do echo waiting for mysql; sleep 2; done]# 2. 初始化数据-name:init-dataimage:busybox:1.28command:[sh,-c,echo Initial data /data/init.txt]volumeMounts:-name:data-dirmountPath:/data# 3. 执行数据库迁移-name:db-migrationimage:alpine:3.14command:[sh,-c,python manage.py migrate]volumes:-name:data-diremptyDir:{}# Init Container特点# 1. 在应用容器之前运行# 2. 按顺序执行前一个成功后才执行下一个# 3. 执行完成后会终止# 4. 如果失败Pod会根据restartPolicy重启3.5 Pod实战示例3.5.1 完整的Pod定义文件# pod-complete.yamlapiVersion:v1kind:Podmetadata:name:complete-pod-demonamespace:defaultlabels:app:nginxenvironment:productionannotations:kubernetes.io/description:Complete Pod examplemaintainer:ops-teamspec:# 调度相关nodeSelector:disktype:ssdgpu:true# 亲和性设置affinity:nodeAffinity:requiredDuringSchedulingIgnoredDuringExecution:nodeSelectorTerms:-matchExpressions:-key:kubernetes.io/archoperator:Invalues:-amd64podAffinity:requiredDuringSchedulingIgnoredDuringExecution:-labelSelector:matchExpressions:-key:appoperator:Invalues:-nginxtopologyKey:kubernetes.io/hostnamepodAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:-weight:100podAffinityTerm:labelSelector:matchExpressions:-key:appoperator:Invalues:-nginxtopologyKey:kubernetes.io/hostname# 容忍度tolerations:-key:node.kubernetes.io/unreachableoperator:Existseffect:NoExecutetolerationSeconds:300# 容器定义containers:-name:nginximage:nginx:1.21.5imagePullPolicy:IfNotPresent# 端口配置ports:-name:httpcontainerPort:80protocol:TCP-name:httpscontainerPort:443protocol:TCP# 资源限制resources:requests:cpu:100mmemory:128Milimits:cpu:500mmemory:256Mi# 环境变量env:-name:NGINX_PORTvalue:80-name:HOSTNAMEvalueFrom:fieldRef:fieldPath:metadata.name# 健康检查livenessProbe:httpGet:path:/port:80initialDelaySeconds:30periodSeconds:10readinessProbe:httpGet:path:/port:80initialDelaySeconds:5periodSeconds:5# 生命周期钩子lifecycle:postStart:exec:command:[/bin/sh,-c,echo Hello from postStart /usr/share/nginx/html/poststart.html]preStop:exec:command:[/bin/sh,-c,nginx -s quit]# 安全上下文securityContext:runAsUser:1000runAsGroup:3000allowPrivilegeEscalation:falsereadOnlyRootFilesystem:truecapabilities:add:[NET_ADMIN,SYS_TIME]drop:[ALL]# 卷挂载volumeMounts:-name:config-volumemountPath:/etc/nginx/nginx.confsubPath:nginx.confreadOnly:true-name:html-volumemountPath:/usr/share/nginx/html# 初始化容器initContainers:-name:init-configimage:busybox:1.28command:[sh,-c,echo Initializing... sleep 5]# 存储卷volumes:-name:config-volumeconfigMap:name:nginx-config-name:html-volumepersistentVolumeClaim:claimName:html-pvc# Pod级别设置restartPolicy:AlwaysterminationGracePeriodSeconds:60hostNetwork:falsehostPID:falsehostIPC:falsednsPolicy:ClusterFirstdnsConfig:nameservers:-1.1.1.1searches:-ns1.svc.cluster.local-my.dns.search.suffixoptions:-name:ndotsvalue:2-name:edns03.5.2 创建和管理Pod# 1. 创建Podkubectl apply -f pod-complete.yaml# 2. 查看Pod状态kubectl get pods -o wide kubectl describe pod complete-pod-demo# 3. 查看Pod日志kubectl logs complete-pod-demo -c nginx# 指定容器kubectl logs -f complete-pod-demo# 实时日志# 4. 进入Pod执行命令kubectlexec-it complete-pod-demo -- /bin/bash kubectlexeccomplete-pod-demo -c nginx -- nginx -v# 5. 调试Podkubectl port-forward complete-pod-demo8080:80# 端口转发kubectl attach complete-pod-demo -i# 附加到运行中的容器# 6. 复制文件kubectlcp/local/path complete-pod-demo:/remote/path kubectlcpcomplete-pod-demo:/remote/path /local/path# 7. 删除Podkubectl delete pod complete-pod-demo kubectl delete -f pod-complete.yaml四、Deployment声明式更新的利器4.1 Deployment核心概念4.1.1 为什么需要DeploymentDeployment解决了Pod管理的几个关键问题// Pod直接管理的问题problems:[]string{1. 缺乏自我修复能力Pod失败后不会自动重启,2. 无法滚动更新更新应用会导致服务中断,3. 难以扩展手动创建多个Pod实例很麻烦,4. 版本回退困难无法轻松回退到之前的版本,}// Deployment提供的解决方案solutions:map[string]string{自我修复:自动替换失败或不可达的Pod,滚动更新:逐步用新版本替换旧版本Pod,弹性伸缩:轻松调整Pod副本数量,版本管理:支持版本历史和回退,发布策略:支持多种更新策略滚动、蓝绿、金丝雀,}4.1.2 Deployment、ReplicaSet和Pod的关系Deployment → ReplicaSet → Pods │ │ │ │ │ ├── Pod 1 │ │ ├── Pod 2 │ │ └── Pod 3 │ │ │ └── ReplicaSet v1 (管理v1版本的Pod) │ └── ReplicaSet v2 (当更新时创建管理v2版本的Pod)# 关系示例apiVersion:apps/v1kind:Deploymentmetadata:name:nginx-deploymentspec:replicas:3selector:matchLabels:app:nginxtemplate:metadata:labels:app:nginxspec:containers:-name:nginximage:nginx:1.21.0# 创建后会产生# 1. 一个Deployment对象# 2. 一个ReplicaSet对象例如nginx-deployment-7c6cf994f7# 3. 三个Pod对象例如nginx-deployment-7c6cf994f7-xxxxx4.2 Deployment配置详解4.2.1 完整的Deployment定义apiVersion:apps/v1kind:Deploymentmetadata:name:nginx-deploymentnamespace:defaultlabels:app:nginxenvironment:productionannotations:deployment.kubernetes.io/revision:1spec:# 副本数replicas:3# 选择器必须匹配template中的labelsselector:matchLabels:app:nginxmatchExpressions:-{key:environment,operator:In,values:[production,staging]}# 策略配置strategy:type:RollingUpdate# 或RecreaterollingUpdate:maxSurge:25%# 最大激增数可以是百分比或具体数字maxUnavailable:25%# 最大不可用数# 最短就绪时间K8s 1.24minReadySeconds:10# 修订历史限制revisionHistoryLimit:10# 进度期限默认600秒progressDeadlineSeconds:600# Pod模板template:metadata:labels:app:nginxversion:1.21.0annotations:sidecar.istio.io/inject:falsespec:containers:-name:nginximage:nginx:1.21.0imagePullPolicy:IfNotPresentports:-containerPort:80resources:requests:cpu:100mmemory:128Milimits:cpu:200mmemory:256MilivenessProbe:httpGet:path:/port:80initialDelaySeconds:30periodSeconds:10readinessProbe:httpGet:path:/port:80initialDelaySeconds:5periodSeconds:5# 容器安全上下文securityContext:privileged:falsereadOnlyRootFilesystem:trueallowPrivilegeEscalation:false# Pod安全上下文securityContext:runAsNonRoot:truerunAsUser:1000runAsGroup:1000fsGroup:1000# 亲和性affinity:podAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:-weight:100podAffinityTerm:labelSelector:matchExpressions:-key:appoperator:Invalues:-nginxtopologyKey:kubernetes.io/hostname# 节点选择器nodeSelector:disktype:ssd# 容忍度tolerations:-key:node.kubernetes.io/not-readyoperator:Existseffect:NoExecutetolerationSeconds:300-key:node.kubernetes.io/unreachableoperator:Existseffect:NoExecutetolerationSeconds:3004.2.2 更新策略详解# 1. 滚动更新RollingUpdate- 默认策略strategy:type:RollingUpdaterollingUpdate:maxSurge:1# 可以超出期望副本数的最大Pod数maxUnavailable:0# 更新过程中不可用Pod的最大数量# 更新过程# 阶段1: 创建1个新Pod因为maxSurge:1总Pod数4# 阶段2: 等待新Pod就绪# 阶段3: 删除1个旧Pod总Pod数3# 阶段4: 重复阶段1-3直到所有Pod更新完成# 2. 重新创建Recreatestrategy:type:Recreate# 更新过程# 阶段1: 删除所有旧Pod# 阶段2: 创建所有新Pod# 特点有服务中断适合不能同时运行多版本的应用4.3 Deployment操作实战4.3.1 创建和查看Deployment# 1. 创建Deploymentkubectl apply -f deployment.yaml# 2. 查看Deployment状态kubectl get deployments kubectl describe deployment nginx-deployment# 3. 查看关联的ReplicaSetkubectl get replicasets -lappnginx kubectl describe replicaset nginx-deployment-7c6cf994f7# 4. 查看Podkubectl get pods -lappnginx kubectl get pods -o wide --show-labels# 5. 查看详细事件kubectl get events --sort-by.metadata.creationTimestamp4.3.2 更新和回滚# 1. 更新镜像版本kubectlsetimage deployment/nginx-deploymentnginxnginx:1.22.0# 或kubectl edit deployment nginx-deployment# 2. 查看更新状态kubectl rollout status deployment nginx-deployment kubectl get deployments -w# 实时监控# 3. 查看更新历史kubectl rollouthistorydeployment nginx-deployment kubectl rollouthistorydeployment nginx-deployment --revision2# 4. 回滚到上一个版本kubectl rollout undo deployment nginx-deployment# 5. 回滚到特定版本kubectl rollout undo deployment nginx-deployment --to-revision1# 6. 暂停和恢复更新kubectl rollout pause deployment nginx-deployment# 进行多个修改...kubectl rollout resume deployment nginx-deployment# 7. 强制回滚当历史记录被清理时kubectl patch deployment nginx-deployment\-p{spec:{template:{spec:{containers:[{name:nginx,image:nginx:1.21.0}]}}}}4.3.3 弹性伸缩# 1. 手动伸缩kubectl scale deployment nginx-deployment --replicas5# 2. 自动伸缩需要Metrics Serverkubectl autoscale deployment nginx-deployment\--min2\--max10\--cpu-percent50# 3. 查看HPAkubectl get hpa kubectl describe hpa nginx-deployment# 4. 删除HPAkubectl delete hpa nginx-deployment4.3.4 高级操作# 1. 金丝雀发布部分更新# 方法1使用两个Deploymentkubectl create deployment nginx-canary --imagenginx:1.22.0 --replicas1# 方法2使用单个Deployment的maxSurge# 设置maxSurge1先更新一个Pod测试# 2. 蓝绿部署# 创建v2 Deploymentkubectl create deployment nginx-v2 --imagenginx:1.22.0 --replicas3# 通过Service切换流量kubectl patchservicenginx-service\-p{spec:{selector:{version:1.22.0}}}# 3. 调试Deployment# 查看详细状态kubectl get deployment nginx-deployment -o yaml kubectl get deployment nginx-deployment -ojsonpath{.status}# 查看控制器事件kubectl get events --field-selector involvedObject.kindDeployment# 4. 生成Deployment配置kubectl create deployment nginx --imagenginx:1.21.0 --dry-runclient -o yamlnginx-deployment.yaml# 5. 导出当前配置kubectl get deployment nginx-deployment -o yaml --exportexported.yaml4.4 Deployment高级特性4.4.1 就绪门Readiness GatesapiVersion:apps/v1kind:Deploymentmetadata:name:readiness-gate-demospec:replicas:3template:metadata:labels:app:nginxspec:# 就绪门readinessGates:-conditionType:www.example.com/feature-availablecontainers:-name:nginximage:nginx:1.21.0# 自定义就绪探针readinessProbe:exec:command:-/bin/sh--c-|# 检查外部条件 if check-external-condition; then # 设置就绪门条件 kubectl patch pod $POD_NAME \ -p {status:{conditions:[{type:www.example.com/feature-available,status:True}]}} fi4.4.2 原地更新In-place Update# Kubernetes 1.27 支持原地更新# 通过改变PodSpec触发重启而不创建新Pod# 1. 启用特性门控# 在kube-apiserver和kubelet中添加# --feature-gatesInPlacePodVerticalScalingtrue# 2. 更新资源请求/限制kubectl patch deployment nginx-deployment\--typejson\-p[{op: replace, path: /spec/template/spec/containers/0/resources, value: {requests: {cpu: 200m, memory: 256Mi}, limits: {cpu: 400m, memory: 512Mi}}}]五、Service服务发现与负载均衡5.1 Service核心概念5.1.1 为什么需要ServicePod是动态的、临时的这带来了几个问题// Pod直接暴露的问题problems:[]string{1. 动态IP: Pod重启后IP地址会改变,2. 负载均衡: 多个Pod实例需要负载均衡,3. 服务发现: 客户端如何发现Pod端点,4. 外部访问: 如何从集群外部访问服务,}// Service的解决方案solutions:map[string]string{稳定端点:提供稳定的虚拟IP和DNS名称,负载均衡:将流量分发到后端Pod,服务发现:通过DNS或环境变量自动发现,外部访问:提供多种外部访问方式,}5.1.2 Service的工作原理Service工作原理示意图 外部客户端 集群内部 │ │ │ ▼ │ ┌─────────────────┐ │ │ Service │ │ │ Virtual IP │ │ │ 10.96.0.10 │ └──────────►│ (ClusterIP) │ └─────────┬───────┘ │ ┌─────────────────┼─────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ Pod 1 │ │ Pod 2 │ │ Pod 3 │ │ 10.244.1.2 │ │ 10.244.1.3 │ │ 10.244.2.2 │ │ :8080 │ │ :8080 │ │ :8080 │ └─────────────┘ └─────────────┘ └─────────────┘# Service创建后Kubernetes会# 1. 分配一个稳定的ClusterIP虚拟IP# 2. 创建Endpoints对象后端Pod列表# 3. 配置kube-proxy创建iptables/IPVS规则# 4. 在CoreDNS中注册DNS记录5.2 Service类型详解5.2.1 ClusterIP默认类型apiVersion:v1kind:Servicemetadata:name:clusterip-servicenamespace:defaultspec:type:ClusterIP# 默认值可省略# 手动指定ClusterIP可选clusterIP:10.96.0.100# 选择器选择后端Podselector:app:nginxenvironment:production# 端口映射ports:-name:httpprotocol:TCPport:80# Service端口targetPort:80# Pod端口# 会话保持Session AffinitysessionAffinity:ClientIPsessionAffinityConfig:clientIP:timeoutSeconds:10800# 3小时# 内部流量策略K8s 1.21internalTrafficPolicy:Local# 或Cluster# 访问方式# 1. 集群内部通过Service名称:端口# http://clusterip-service.default.svc.cluster.local:80# 或简写http://clusterip-service:80## 2. 环境变量注入旧方式# CLUSTERIP_SERVICE_SERVICE_HOST10.96.0.100# CLUSTERIP_SERVICE_SERVICE_PORT805.2.2 NodePortapiVersion:v1kind:Servicemetadata:name:nodeport-servicespec:type:NodePortselector:app:nginxports:-name:httpprotocol:TCPport:80# Service端口targetPort:80# Pod端口nodePort:30080# 节点端口30000-32767# 指定外部流量策略externalTrafficPolicy:Local# 或Cluster# 访问方式# 1. 通过任何节点的IP:NodePort访问# http://任何节点IP:30080## 2. 集群内部仍然可以通过ClusterIP访问## externalTrafficPolicy说明# - Local: 只将流量路由到运行Pod的节点保留客户端IP# - Cluster: 可以将流量路由到其他节点客户端IP被替换5.2.3 LoadBalancerapiVersion:v1kind:Servicemetadata:name:loadbalancer-serviceannotations:# 云提供商特定注解service.beta.kubernetes.io/aws-load-balancer-type:nlbservice.beta.kubernetes.io/azure-load-balancer-internal:truecloud.google.com/load-balancer-type:Internalspec:type:LoadBalancerselector:app:nginxports:-name:httpprotocol:TCPport:80targetPort:80# 分配特定IP如果云提供商支持loadBalancerIP:203.0.113.10# 指定源IP范围白名单loadBalancerSourceRanges:-203.0.113.0/24-192.168.0.0/16# 工作原理# 1. Kubernetes创建NodePort Service# 2. 云控制器管理器创建云负载均衡器# 3. 负载均衡器将流量转发到节点端口# 4. 节点上的kube-proxy将流量转发到Pod5.2.4 ExternalNameapiVersion:v1kind:Servicemetadata:name:external-servicespec:type:ExternalName# 外部服务的域名externalName:api.example.com# 注意ExternalName Service没有选择器# 也没有端口定义# 工作原理# 将external-service.default.svc.cluster.local# CNAME解析到api.example.com## 使用场景# 1. 迁移服务到Kubernetes时作为代理# 2. 访问外部服务时使用统一的命名5.3 Service配置进阶5.3.1 多端口ServiceapiVersion:v1kind:Servicemetadata:name:multi-port-servicespec:selector:app:myappports:-name:httpprotocol:TCPport:80targetPort:8080-name:httpsprotocol:TCPport:443targetPort:8443-name:metricsprotocol:TCPport:9090targetPort:9090-name:grpcprotocol:TCPport:50051targetPort:50051# DNS记录# multi-port-service.default.svc.cluster.local# SRV记录会包含所有端口信息5.3.2 无选择器的Service# 1. 创建没有选择器的ServiceapiVersion:v1kind:Servicemetadata:name:no-selector-servicespec:ports:-name:httpprotocol:TCPport:80targetPort:8080# 没有selector字段# 2. 手动创建EndpointsapiVersion:v1kind:Endpointsmetadata:name:no-selector-service# 必须与Service同名subsets:-addresses:-ip:192.168.1.100nodeName:node-1# 可选targetRef:# 可选kind:Podname:external-pod-1namespace:default-ip:192.168.1.101ports:-name:httpport:8080protocol:TCP# 使用场景# 1. 连接外部数据库# 2. 连接另一个集群的服务# 3. 迁移过程中连接传统系统5.3.3 Headless ServiceapiVersion:v1kind:Servicemetadata:name:headless-servicespec:clusterIP:None# 关键设置selector:app:stateful-appports:-name:httpprotocol:TCPport:80targetPort:8080# 特点# 1. 没有ClusterIP# 2. DNS返回所有Pod的IP地址A记录# 3. 客户端直接连接到Pod不经过负载均衡## DNS查询结果# headless-service.default.svc.cluster.local# 返回# - 10.244.1.2# - 10.244.1.3# - 10.244.2.2## 使用场景# 1. StatefulSet需要稳定的网络标识# 2. 客户端需要直接连接到特定Pod# 3. 数据库集群等有状态应用5.4 Service实战操作5.4.1 创建和管理Service# 1. 创建Servicekubectl apply -f service.yaml# 2. 查看Servicekubectl get services kubectl describeservicemy-service# 3. 查看Endpointskubectl get endpoints kubectl describe endpoints my-service# 4. 查看Service的DNS信息kubectl run -it --rm dns-test --imagebusybox:1.28 --restartNever --nslookupmy-service# 5. 测试Service连通性kubectl run -it --rm test-client --imagebusybox:1.28 --restartNever --wget-O- http://my-service:80# 6. 端口转发调试用kubectl port-forward service/my-service8080:80# 7. 暴露Deployment为Servicekubectl expose deployment nginx-deployment --port80--target-port80--typeNodePort# 8. 编辑Servicekubectl editservicemy-service5.5 Service与Ingress5.5.1 Ingress基础Service只能提供L4负载均衡Ingress提供L7HTTP/HTTPS路由。# 1. 部署Ingress Controller以Nginx为例# https://kubernetes.github.io/ingress-nginx/deploy/# 2. 创建Ingress资源apiVersion:networking.k8s.io/v1kind:Ingressmetadata:name:example-ingressannotations:nginx.ingress.kubernetes.io/rewrite-target:/nginx.ingress.kubernetes.io/ssl-redirect:truespec:tls:-hosts:-example.comsecretName:example-tlsrules:-host:example.comhttp:paths:-path:/apipathType:Prefixbackend:service:name:api-serviceport:number:80-path:/webpathType:Prefixbackend:service:name:web-serviceport:number:80-host:admin.example.comhttp:paths:-path:/pathType:Prefixbackend:service:name:admin-serviceport:number:80# 3. Service配置apiVersion:v1kind:Servicemetadata:name:api-servicespec:selector:app:apiports:-name:httpport:80targetPort:80805.5.2 Service与Ingress对比特性ServiceIngress工作层L4传输层L7应用层协议支持TCP/UDP/SCTPHTTP/HTTPS部分支持TCP/UDP路由能力基于IP和端口基于主机名、路径、请求头等SSL终止不支持支持负载均衡算法简单轮询/会话保持多种算法轮询、最少连接等使用场景内部服务通信、基本暴露外部HTTP/HTTPS流量管理六、总结与面试准备6.1 核心概念关系总结6.1.1 Pod、Deployment、Service协作流程完整应用部署流程 1. 开发者编写Deployment YAML ↓ 2. kubectl apply创建Deployment ↓ 3. Deployment创建ReplicaSet ↓ 4. ReplicaSet创建和管理Pod ↓ 5. Pod调度到节点并运行容器 ↓ 6. Service根据选择器发现Pod ↓ 7. Service创建EndpointsPod IP列表 ↓ 8. kube-proxy配置负载均衡规则 ↓ 9. CoreDNS注册Service DNS记录 ↓ 10. 应用可通过Service名称访问后端Pod6.1.2 三者的职责划分typePodstruct{职责:运行容器实例,特点:临时性、动态IP、可扩展,生命周期:创建、运行、终止,}typeDeploymentstruct{职责:声明式管理Pod副本,特点:滚动更新、回滚、弹性伸缩,管理对象:通过ReplicaSet管理Pod,}typeServicestruct{职责:服务发现和负载均衡,特点:稳定端点、多种类型、DNS名称,作用对象:通过选择器关联Pod,}// 三者关系总结关系模型:{Deployment:管理Pod的期望状态,Pod:实际运行的工作负载,Service:暴露和访问Pod的入口,}6.2 面试高频问题解析Q1: Pod和Deployment有什么区别参考答案抽象层级不同Pod是Kubernetes中最小的调度单元直接运行容器Deployment是更高层次的抽象用于管理Pod的副本集生命周期管理Pod是临时的重启后IP会改变没有自我修复能力Deployment确保指定数量的Pod副本持续运行具有自我修复能力更新策略Pod不支持滚动更新只能删除重建Deployment支持多种更新策略滚动更新、重新创建使用场景Pod适合一次性任务、调试、测试Deployment适合生产环境的无状态应用实际关系# Deployment创建和管理PodDeployment → ReplicaSet → Pods# 示例创建一个Deploymentkubectl create deployment nginx --imagenginx:1.21# 这会创建# 1. 一个Deployment对象# 2. 一个ReplicaSet对象# 3. 一个Pod对象默认replicas1Q2: Service的ClusterIP、NodePort、LoadBalancer有什么区别参考答案ClusterIP默认类型只在集群内部访问分配一个稳定的虚拟IPVIP通过kube-proxy实现内部负载均衡访问方式服务名.命名空间.svc.cluster.localNodePort在ClusterIP基础上在每个节点上开放一个端口端口范围30000-32767可以从集群外部通过节点IP:NodePort访问实际生产中通常配合外部负载均衡器使用LoadBalancer在NodePort基础上集成云提供商的负载均衡器自动创建外部负载均衡器并分配公网IP云提供商特定功能可通过annotations配置成本较高适用于生产环境选择建议选择策略-集群内部访问使用ClusterIP-开发测试环境使用NodePort-生产环境云平台使用LoadBalancer-生产环境裸机使用NodePort 外部负载均衡器Q3: 如何实现零停机部署参考答案使用Deployment的滚动更新strategy:type:RollingUpdaterollingUpdate:maxSurge:1# 先启动一个新PodmaxUnavailable:0# 保证始终有可用Pod配置合适的健康检查readinessProbe:httpGet:path:/healthport:8080initialDelaySeconds:5periodSeconds:5successThreshold:1failureThreshold:3livenessProbe:httpGet:path:/healthport:8080initialDelaySeconds:30# 给应用足够的启动时间periodSeconds:10使用minReadySecondsminReadySeconds:30# 新Pod就绪后等待30秒才认为可用配置Pod Disruption BudgetPDBapiVersion:policy/v1kind:PodDisruptionBudgetmetadata:name:app-pdbspec:minAvailable:2# 保证至少2个Pod可用selector:matchLabels:app:myapp更新流程# 1. 先更新一个Pod金丝雀发布kubectlsetimage deployment/appappapp:v2.0.0# 2. 监控新Pod状态kubectl rollout status deployment/app# 3. 如果正常继续更新剩余Pod# 4. 如果有问题立即回滚kubectl rollout undo deployment/appQ4: Service如何实现负载均衡参考答案kube-proxy的工作模式iptables模式默认通过iptables规则实现负载均衡IPVS模式使用IPVSIP Virtual Server实现高性能负载均衡userspace模式已弃用在用户空间实现代理负载均衡算法# iptables模式随机选择random# IPVS模式支持多种算法# - rr: 轮询# - lc: 最少连接# - dh: 目标哈希# - sh: 源哈希# - sed: 最短预期延迟# - nq: 从不排队会话保持sessionAffinity:ClientIPsessionAffinityConfig:clientIP:timeoutSeconds:10800内部流量策略internalTrafficPolicy:Local# 优先将流量保持在节点内部实际工作流程客户端请求 → Service ClusterIP → iptables/IPVS规则 ↓ 根据负载均衡算法选择后端Pod ↓ 转发到Pod IP:PortQ5: 如何调试Pod无法启动的问题参考答案# 系统化的调试流程1. 查看Pod状态 kubectl get pods -o wide kubectl describe podpod-name2. 查看Pod事件 kubectl get events --field-selector involvedObject.namepod-name3. 检查Pod调度 kubectl describe podpod-name|grep-A10 Events4. 查看节点资源 kubectl describe nodenode-namekubectl get nodes -o wide5. 检查镜像拉取 kubectl describe podpod-name|grep-i image kubectl get pods -ojsonpath{range .items[*]}{.status.containerStatuses[*].state.waiting.reason}{\n}{end}6. 检查存储卷 kubectl describe podpod-name|grep-i volume kubectl get pvc7. 检查配置映射和密钥 kubectl get configmaps kubectl get secrets8. 检查网络策略 kubectl get networkpolicies9. 检查资源配额 kubectl describequota-nnamespace10. 查看Kubelet日志在节点上 journalctl -u kubelet --since10 minutes ago6.3 实战面试题题目设计一个高可用的Web应用部署架构要求应用需要运行3个副本支持零停机部署可以从公网访问需要监控和健康检查配置和密钥需要安全管理参考答案# 1. 配置映射ConfigMapapiVersion:v1kind:ConfigMapmetadata:name:webapp-configdata:APP_ENV:productionLOG_LEVEL:infoFEATURE_FLAGS:new-ui,beta-api# 2. 密钥SecretapiVersion:v1kind:Secretmetadata:name:webapp-secretstype:Opaquedata:DATABASE_URL:base64编码API_KEY:base64编码# 3. 部署DeploymentapiVersion:apps/v1kind:Deploymentmetadata:name:webapp-deploymentspec:replicas:3revisionHistoryLimit:5strategy:type:RollingUpdaterollingUpdate:maxSurge:1maxUnavailable:0selector:matchLabels:app:webapptemplate:metadata:labels:app:webappversion:v1.0.0spec:containers:-name:webappimage:myapp:1.0.0imagePullPolicy:IfNotPresentports:-containerPort:8080env:-name:APP_ENVvalueFrom:configMapKeyRef:name:webapp-configkey:APP_ENV-name:DATABASE_URLvalueFrom:secretKeyRef:name:webapp-secretskey:DATABASE_URLresources:requests:cpu:100mmemory:128Milimits:cpu:200mmemory:256MilivenessProbe:httpGet:path:/healthport:8080initialDelaySeconds:30periodSeconds:10readinessProbe:httpGet:path:/readyport:8080initialDelaySeconds:5periodSeconds:5startupProbe:httpGet:path:/healthport:8080failureThreshold:30periodSeconds:10affinity:podAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:-weight:100podAffinityTerm:labelSelector:matchExpressions:-key:appoperator:Invalues:-webapptopologyKey:kubernetes.io/hostname# 4. 服务ServiceapiVersion:v1kind:Servicemetadata:name:webapp-servicespec:selector:app:webappports:-name:httpprotocol:TCPport:80targetPort:8080type:ClusterIP# 5. 入口IngressapiVersion:networking.k8s.io/v1kind:Ingressmetadata:name:webapp-ingressannotations:nginx.ingress.kubernetes.io/ssl-redirect:truespec:tls:-hosts:-myapp.example.comsecretName:tls-secretrules:-host:myapp.example.comhttp:paths:-path:/pathType:Prefixbackend:service:name:webapp-serviceport:number:80# 6. 水平Pod自动伸缩HPAapiVersion:autoscaling/v2kind:HorizontalPodAutoscalermetadata:name:webapp-hpaspec:scaleTargetRef:apiVersion:apps/v1kind:Deploymentname:webapp-deploymentminReplicas:3maxReplicas:10metrics:-type:Resourceresource:name:cputarget:type:UtilizationaverageUtilization:50-type:Resourceresource:name:memorytarget:type:UtilizationaverageUtilization:70# 7. Pod中断预算PDBapiVersion:policy/v1kind:PodDisruptionBudgetmetadata:name:webapp-pdbspec:minAvailable:2selector:matchLabels:app:webapp6.4 学习路径建议6.4.1 初学者学习路线第一阶段基础概念1-2周 - 理解Pod、Deployment、Service核心概念 - 掌握kubectl基本命令 - 能够在Minikube或Kind上运行简单应用 第二阶段进阶使用2-4周 - 学习ConfigMap、Secret、Volume - 掌握健康检查、资源限制 - 理解滚动更新和回滚 - 学习基本的故障排查 第三阶段生产实践4-8周 - 学习Ingress、HPA、PDB - 理解网络策略和安全上下文 - 掌握监控和日志收集 - 学习Helm包管理 第四阶段高级主题8-12周 - StatefulSet、DaemonSet、Job/CronJob - 自定义资源定义CRD和Operator - 服务网格Istio/Linkerd - 多集群管理6.4.2 推荐资源官方文档Kubernetes官方文档Kubernetes API参考Kubernetes任务指南实践环境Minikube本地单节点集群KindKubernetes in DockerK3s轻量级Kubernetes各大云平台的Kubernetes服务EKS、AKS、GKE认证和课程CKADCertified Kubernetes Application DeveloperCKACertified Kubernetes AdministratorKubernetes官方培训课程6.5 常见陷阱和最佳实践6.5.1 常见陷阱# 陷阱1忘记设置资源限制containers:-name:appimage:myapp:latest# 缺少resources设置可能导致节点资源耗尽# 陷阱2健康检查配置不当livenessProbe:httpGet:path:/port:8080initialDelaySeconds:5# 太短应用可能还没启动periodSeconds:1# 太频繁增加压力# 陷阱3标签选择器不匹配apiVersion:apps/v1kind:Deploymentmetadata:name:appspec:selector:matchLabels:app:myapptemplate:metadata:labels:app:different-app# 错误选择器无法匹配# 陷阱4使用latest标签image:nginx:latest# 可能导致版本不一致和更新问题# 陷阱5缺少Pod反亲和性# 所有副本可能调度到同一个节点节点故障时服务完全中断6.5.2 最佳实践清单✓ 总是设置资源请求和限制 ✓ 配置合适的健康检查 ✓ 使用有意义的标签和注解 ✓ 指定具体的镜像标签避免latest ✓ 配置Pod反亲和性提高可用性 ✓ 使用ConfigMap和Secret管理配置 ✓ 为生产环境配置PDB ✓ 启用自动伸缩HPA ✓ 实施网络策略限制流量 ✓ 使用非root用户运行容器 ✓ 只读根文件系统 ✓ 定期更新Kubernetes版本 ✓ 实施备份和灾难恢复策略 ✓ 监控和告警配置 ✓ 安全上下文配置最后的建议Kubernetes是一个复杂的系统但掌握其核心概念Pod、Deployment、Service是构建云原生应用的基础。建议从实际动手开始先在小规模环境中实践逐步深入理解各个组件的工作原理和最佳实践。记住学习Kubernetes是一个持续的过程随着生态系统的不断发展总有新的东西需要学习。