深入理解k8s中Pod、Deployment和Service--图文篇
一、Pod、Deployment和Service的角色关系
k8s集群中,Deployment、Pod、Service是最重要的三个概念之一。对于新手如何理解它们的职责呢嗯?
下面的图形是对它们关系的形象总结。
Pod 是牛马打工人,永远有负载运行。
Deployment 是创建Pod 和控制副本数的对象,Pod 要岁时随刻满足它的期望状态。所以它就是纪律管理员,Pod数量永远要保证出勤和数量。可以说它天生有强烈的控制欲望。
对于Service服务,它既是一组pod 的流量入口,也是对外发布信息的“网关”。就好比酒店大堂的总接待人。具体任务过来,它会分配给后端某个具体的Pod。
二、Pod、Deployment和Service的Spec配置
Kubernetes 的核心设计思想是 “声明式 API”:用户通过 YAML 声明资源应该达到的状态。
所有资源(如 Pod、Deployment、Service、ConfigMap 等)的 YAML 配置中,spec是核心字段之一,定义了资源的 “期望“状态。
以上三种资源最重要的定义部分,都罗列到这张图里了,记得收藏哦!
2.1 Pod中spec定义部分
Pod的完整示例:
apiVersion: v1
kind: Pod
metadata:name: production-web-applabels:app: web-apptier: frontendversion: v1.2.3annotations:kubernetes.io/change-cause: "Deploy version v1.2.3 with security fixes"prometheus.io/scrape: "true"prometheus.io/port: "8080"
spec:# 调度配置nodeSelector:node-type: optimized-webaffinity:podAntiAffinity:requiredDuringSchedulingIgnoredDuringExecution:- labelSelector:matchExpressions:- key: appoperator: Invalues:- web-apptopologyKey: kubernetes.io/hostname# 安全配置serviceAccountName: web-app-sasecurityContext:runAsUser: 1001runAsGroup: 1001fsGroup: 1001runAsNonRoot: trueseccompProfile:type: RuntimeDefault# 存储配置volumes:- name: app-configconfigMap:name: web-app-configdefaultMode: 0644- name: tmp-volumeemptyDir:medium: MemorysizeLimit: 128Mi- name: tls-secretssecret:secretName: web-app-tlsdefaultMode: 0600# 初始化容器initContainers:- name: init-configimage: busybox:1.35command: ['sh', '-c', 'echo "Waiting for config..." && until [ -f /etc/config/ready ]; do sleep 2; done']volumeMounts:- name: app-configmountPath: /etc/configsecurityContext:runAsUser: 1001allowPrivilegeEscalation: false# 主容器containers:- name: web-appimage: my-registry/app/web:v1.2.3imagePullPolicy: IfNotPresent# 资源限制resources:requests:cpu: 500mmemory: 512Miephemeral-storage: 1Gilimits:cpu: 1000mmemory: 1024Miephemeral-storage: 2Gi# 端口配置ports:- name: httpcontainerPort: 8080protocol: TCP- name: metricscontainerPort: 9090protocol: TCP# 环境变量env:- name: APP_ENVvalue: "production"- name: LOG_LEVELvalue: "info"- name: CONFIG_PATHvalue: "/etc/app/config"- name: NODE_NAMEvalueFrom:fieldRef:fieldPath: spec.nodeName- name: POD_IPvalueFrom:fieldRef:fieldPath: status.podIP# 健康检查livenessProbe:httpGet:path: /healthzport: 8080httpHeaders:- name: X-Health-Checkvalue: "liveness"initialDelaySeconds: 45timeoutSeconds: 3periodSeconds: 10failureThreshold: 3readinessProbe:httpGet:path: /readyzport: 8080initialDelaySeconds: 5timeoutSeconds: 2periodSeconds: 5successThreshold: 1failureThreshold: 2startupProbe:httpGet:path: /healthzport: 8080failureThreshold: 30periodSeconds: 10# 生命周期钩子lifecycle:postStart:exec:command:- "/bin/sh"- "-c"- |echo "Pod $POD_NAME started on $NODE_NAME" > /tmp/startup.logpreStop:httpGet:path: /prestopport: 8080# 存储挂载volumeMounts:- name: app-configmountPath: /etc/app/configreadOnly: true- name: tmp-volumemountPath: /tmp- name: tls-secretsmountPath: /etc/tlsreadOnly: true# 容器安全上下文securityContext:allowPrivilegeEscalation: falserunAsNonRoot: truerunAsUser: 1001capabilities:drop:- ALLreadOnlyRootFilesystem: true# Pod 级别配置restartPolicy: AlwaysterminationGracePeriodSeconds: 60dnsPolicy: ClusterFirsthostNetwork: falsehostPID: falsehostIPC: falseimagePullSecrets:- name: registry-credentials
2.2 Deployment中spec定义部分
以下是一个包含上述主要配置的 Deployment 完整 YAML:
apiVersion: apps/v1
kind: Deployment
metadata:name: nginx-deployment
spec:replicas: 3selector:matchLabels:app: nginxstrategy:type: RollingUpdaterollingUpdate:maxSurge: 1maxUnavailable: 0minReadySeconds: 5revisionHistoryLimit: 5template:metadata:labels:app: nginxspec:containers:- name: nginximage: nginx:1.21ports:- containerPort: 80resources:requests:cpu: "100m"memory: "128Mi"limits:cpu: "200m"memory: "256Mi"
3.3 Service的spec定义部分
以下是一个包含上述主要配置的service完整yaml:
apiVersion: v1
kind: Service
metadata:name: production-web-servicenamespace: web-productionlabels:app: web-applicationenvironment: productionannotations:# 云厂商特定注解service.beta.kubernetes.io/aws-load-balancer-type: "nlb"service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true"service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:us-west-2:123456789012:certificate/xxxxxx"# 运维相关注解prometheus.io/scrape: "true"prometheus.io/port: "9090"
spec:# 服务类型配置type: LoadBalancer# 选择器 - 关联后端 Podselector:app: web-frontendcomponent: api-serverenvironment: productionversion: v2.1.3# 端口映射配置ports:- name: http-webprotocol: TCPport: 80targetPort: 8080appProtocol: http- name: https-webprotocol: TCPport: 443targetPort: 8443appProtocol: https- name: metricsprotocol: TCPport: 9090targetPort: 9090appProtocol: http # 指标端点通常使用 HTTP- name: grpc-apiprotocol: TCPport: 50051targetPort: 50051appProtocol: grpc# IP 地址配置clusterIP: 10.96.105.150 # 固定 ClusterIP,便于防火墙规则loadBalancerIP: 203.0.113.25 # 预留的负载均衡器 IP# 外部 IP(用于混合云或特定网络场景)externalIPs:- 192.168.1.200- 192.168.1.201# 会话保持配置sessionAffinity: ClientIPsessionAffinityConfig:clientIP:timeoutSeconds: 10800 # 3小时会话保持# 流量策略externalTrafficPolicy: Local # 保留客户端源 IP,流量只路由到本地节点 PodinternalTrafficPolicy: Cluster # 内部流量在集群内所有 Pod 间负载均衡# 健康检查配置(NodePort 类型相关)healthCheckNodePort: 32456 # 自定义健康检查端口# 负载均衡器源范围限制loadBalancerSourceRanges:- 203.0.113.0/24- 198.51.100.0/24- 192.168.0.0/16