【Kubernets】Kubernetes 资源类型大全:使用场景与配置示例
Kubernetes 资源类型大全:使用场景与配置示例
- Kubernetes 资源类型大全:使用场景与配置示例
- 一、核心资源类型概览
- 二、工作负载资源(Workload Resources)
- 1. Pod
- 2. Deployment
- 3. StatefulSet
- 4. DaemonSet
- 5. Job
- 6. CronJob
- 7. ReplicaSet
- 三、服务发现与负载均衡资源
- 1. Service
- 2. Ingress
- 3. Endpoints/EndpointSlice
- 四、配置资源
- 1. ConfigMap
- 2. Secret
- 五、存储资源
- 1. PersistentVolume (PV)
- 2. PersistentVolumeClaim (PVC)
- 3. StorageClass
- 六、安全资源
- 1. ServiceAccount
- 2. Role / ClusterRole
- 3. RoleBinding / ClusterRoleBinding
- 七、集群资源
- 1. Namespace
- 2. ResourceQuota
- 3. LimitRange
- 八、扩展资源
- 1. HorizontalPodAutoscaler (HPA)
- 2. VerticalPodAutoscaler (VPA)
- 3. NetworkPolicy
- 九、自定义资源 (Custom Resources)
- 1. CustomResourceDefinition (CRD)
- 2. 自定义资源实例
- 十、其他重要资源
- 1. PodDisruptionBudget
- 2. PriorityClass
- 3. RuntimeClass
- 十一、资源类型速查表
- 十二、最佳实践总结
Kubernetes 资源类型大全:使用场景与配置示例
一、核心资源类型概览
二、工作负载资源(Workload Resources)
1. Pod
使用场景:最小部署单元,单容器或多容器应用
# pod-example.yaml
apiVersion: v1
kind: Pod
metadata:name: nginx-podlabels:app: nginx
spec:containers:- name: nginximage: nginx:1.21ports:- containerPort: 80env:- name: ENV_VARvalue: "production"resources:requests:memory: "64Mi"cpu: "250m"limits:memory: "128Mi"cpu: "500m"# 多容器示例- name: log-collectorimage: busyboxcommand: ['sh', '-c', 'tail -f /dev/null']
2. Deployment
使用场景:无状态应用部署,支持滚动更新、回滚
# deployment-example.yaml
apiVersion: apps/v1
kind: Deployment
metadata:name: web-applabels:app: web
spec:replicas: 3selector:matchLabels:app: webstrategy:type: RollingUpdaterollingUpdate:maxSurge: 25%maxUnavailable: 25%template:metadata:labels:app: webspec:containers:- name: webimage: nginx:1.21ports:- containerPort: 80livenessProbe:httpGet:path: /port: 80initialDelaySeconds: 30periodSeconds: 10readinessProbe:httpGet:path: /port: 80initialDelaySeconds: 5periodSeconds: 5resources:requests:cpu: 100mmemory: 128Milimits:cpu: 500mmemory: 512Mi
3. StatefulSet
使用场景:有状态应用,需要稳定网络标识、持久化存储
# statefulset-example.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:name: mysql
spec:serviceName: "mysql"replicas: 3selector:matchLabels:app: mysqltemplate:metadata:labels:app: mysqlspec:containers:- name: mysqlimage: mysql:8.0ports:- containerPort: 3306env:- name: MYSQL_ROOT_PASSWORDvalueFrom:secretKeyRef:name: mysql-secretkey: passwordvolumeMounts:- name: mysql-datamountPath: /var/lib/mysqlvolumeClaimTemplates:- metadata:name: mysql-dataspec:accessModes: [ "ReadWriteOnce" ]storageClassName: "fast-ssd"resources:requests:storage: 20Gi
4. DaemonSet
使用场景:每个节点运行一个副本(日志收集、节点监控)
# daemonset-example.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:name: fluentd-logginglabels:k8s-app: fluentd-logging
spec:selector:matchLabels:name: fluentd-loggingtemplate:metadata:labels:name: fluentd-loggingspec:tolerations:- key: node-role.kubernetes.io/mastereffect: NoSchedulecontainers:- name: fluentdimage: fluent/fluentd:v1.14resources:limits:memory: 200Mirequests:cpu: 100mmemory: 200MivolumeMounts:- name: varlogmountPath: /var/log- name: varlibdockercontainersmountPath: /var/lib/docker/containersreadOnly: trueterminationGracePeriodSeconds: 30volumes:- name: varloghostPath:path: /var/log- name: varlibdockercontainershostPath:path: /var/lib/docker/containers
5. Job
使用场景:一次性任务、批处理作业
# job-example.yaml
apiVersion: batch/v1
kind: Job
metadata:name: pi-calculation
spec:completions: 5 # 需要完成5个Podparallelism: 2 # 同时运行2个PodbackoffLimit: 4 # 重试次数template:spec:containers:- name: piimage: perl:5.34command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]restartPolicy: Never
6. CronJob
使用场景:定时任务、周期性作业
# cronjob-example.yaml
apiVersion: batch/v1
kind: CronJob
metadata:name: database-backup
spec:schedule: "0 2 * * *" # 每天凌晨2点startingDeadlineSeconds: 200concurrencyPolicy: Forbid # 禁止并发执行jobTemplate:spec:template:spec:containers:- name: backupimage: postgres:13command:- /bin/sh- -c- pg_dump -h db-host -U postgres mydb > /backup/backup.sqlenv:- name: PGPASSWORDvalueFrom:secretKeyRef:name: postgres-secretkey: passwordvolumeMounts:- name: backup-volumemountPath: /backupvolumes:- name: backup-volumepersistentVolumeClaim:claimName: backup-pvcrestartPolicy: OnFailure
7. ReplicaSet
使用场景:Pod副本管理(Deployment底层使用)
# replicaset-example.yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:name: frontendlabels:app: guestbooktier: frontend
spec:replicas: 3selector:matchLabels:tier: frontendtemplate:metadata:labels:tier: frontendspec:containers:- name: php-redisimage: gcr.io/google_samples/gb-frontend:v3resources:requests:cpu: 100mmemory: 100Mienv:- name: GET_HOSTS_FROMvalue: dnsports:- containerPort: 80
三、服务发现与负载均衡资源
1. Service
使用场景:服务发现、负载均衡、网络访问抽象
# service-example.yaml
apiVersion: v1
kind: Service
metadata:name: web-service
spec:selector:app: webports:- name: httpport: 80targetPort: 8080protocol: TCP- name: httpsport: 443targetPort: 8443protocol: TCPtype: LoadBalancer # ClusterIP, NodePort, LoadBalancer# 外部负载均衡器配置externalTrafficPolicy: LocalloadBalancerIP: 192.168.1.100
2. Ingress
使用场景:HTTP/HTTPS路由、域名基于的路由、SSL终止
# ingress-example.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:name: example-ingressannotations:nginx.ingress.kubernetes.io/rewrite-target: /cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:tls:- hosts:- app.example.comsecretName: example-tlsrules:- host: app.example.comhttp:paths:- path: /pathType: Prefixbackend:service:name: web-serviceport:number: 80- path: /apipathType: Prefixbackend:service:name: api-serviceport:number: 8080
3. Endpoints/EndpointSlice
使用场景:手动配置服务端点
# endpoints-example.yaml
apiVersion: v1
kind: Endpoints
metadata:name: external-service
subsets:
- addresses:- ip: 192.168.1.100- ip: 192.168.1.101ports:- port: 80name: http
四、配置资源
1. ConfigMap
使用场景:配置数据存储、环境变量、配置文件
# configmap-example.yaml
apiVersion: v1
kind: ConfigMap
metadata:name: app-config
data:# 简单键值对log-level: "info"database-url: "postgresql://localhost:5432/mydb"# 配置文件nginx.conf: |server {listen 80;server_name localhost;location / {proxy_pass http://backend;}}# 属性文件application.properties: |server.port=8080spring.datasource.url=jdbc:mysql://localhost:3306/mydb
2. Secret
使用场景:敏感信息存储(密码、令牌、密钥)
# secret-example.yaml
apiVersion: v1
kind: Secret
metadata:name: app-secrets
type: Opaque
data:# Base64编码的数据username: YWRtaW4=password: cGFzc3dvcmQxMjM=database-url: cG9zdGdyZXNxbDovL3VzZXI6cGFzc0BkYjoxMjM0L2RibmFtZQ==# 使用TLS Secret
apiVersion: v1
kind: Secret
metadata:name: tls-secret
type: kubernetes.io/tls
data:tls.crt: <base64编码的证书>tls.key: <base64编码的私钥>
五、存储资源
1. PersistentVolume (PV)
使用场景:集群范围的存储资源
# persistentvolume-example.yaml
apiVersion: v1
kind: PersistentVolume
metadata:name: pv-volumelabels:type: local
spec:capacity:storage: 10GiaccessModes:- ReadWriteOncepersistentVolumeReclaimPolicy: RetainstorageClassName: slowhostPath:path: "/mnt/data"
2. PersistentVolumeClaim (PVC)
使用场景:用户对存储的请求
# persistentvolumeclaim-example.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:name: pv-claim
spec:storageClassName: slowaccessModes:- ReadWriteOnceresources:requests:storage: 3Gi
3. StorageClass
使用场景:动态卷配置、存储类别定义
# storageclass-example.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:name: fast-ssd
provisioner: kubernetes.io/gce-pd
parameters:type: pd-ssdreplication-type: none
allowVolumeExpansion: true
mountOptions:- discard
六、安全资源
1. ServiceAccount
使用场景:Pod身份认证、API访问控制
# serviceaccount-example.yaml
apiVersion: v1
kind: ServiceAccount
metadata:name: build-robotnamespace: default
secrets:
- name: build-robot-token-xyz
2. Role / ClusterRole
使用场景:命名空间/集群范围的权限定义
# role-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:namespace: defaultname: pod-reader
rules:
- apiGroups: [""]resources: ["pods"]verbs: ["get", "watch", "list"]# clusterrole-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:name: cluster-admin
rules:
- apiGroups: [""]resources: ["*"]verbs: ["*"]
- apiGroups: ["*"]resources: ["*"]verbs: ["*"]
3. RoleBinding / ClusterRoleBinding
使用场景:角色绑定到主体
# rolebinding-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:name: read-podsnamespace: default
subjects:
- kind: Username: janeapiGroup: rbac.authorization.k8s.io
roleRef:kind: Rolename: pod-readerapiGroup: rbac.authorization.k8s.io
七、集群资源
1. Namespace
使用场景:资源隔离、多租户环境
# namespace-example.yaml
apiVersion: v1
kind: Namespace
metadata:name: productionlabels:name: productionenvironment: prod
2. ResourceQuota
使用场景:资源配额限制
# resourcequota-example.yaml
apiVersion: v1
kind: ResourceQuota
metadata:name: compute-resourcesnamespace: production
spec:hard:requests.cpu: "1"requests.memory: 1Gilimits.cpu: "2"limits.memory: 2Girequests.storage: 10Gipersistentvolumeclaims: "4"services.loadbalancers: "2"services.nodeports: "0"
3. LimitRange
使用场景:限制资源请求和限制的默认值
# limitrange-example.yaml
apiVersion: v1
kind: LimitRange
metadata:name: mem-limit-rangenamespace: production
spec:limits:- default:memory: 512Micpu: 500mdefaultRequest:memory: 256Micpu: 100mtype: Container
八、扩展资源
1. HorizontalPodAutoscaler (HPA)
使用场景:基于CPU/内存使用率自动扩缩容
# hpa-example.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:name: web-app-hpa
spec:scaleTargetRef:apiVersion: apps/v1kind: Deploymentname: web-appminReplicas: 2maxReplicas: 10metrics:- type: Resourceresource:name: cputarget:type: UtilizationaverageUtilization: 50- type: Resourceresource:name: memorytarget:type: UtilizationaverageUtilization: 80behavior:scaleDown:stabilizationWindowSeconds: 300policies:- type: Percentvalue: 50periodSeconds: 60
2. VerticalPodAutoscaler (VPA)
使用场景:自动调整Pod资源请求
# vpa-example.yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:name: web-app-vpa
spec:targetRef:apiVersion: "apps/v1"kind: Deploymentname: web-appupdatePolicy:updateMode: "Auto"resourcePolicy:containerPolicies:- containerName: "*"minAllowed:cpu: 100mmemory: 50MimaxAllowed:cpu: 1memory: 1GicontrolledResources: ["cpu", "memory"]
3. NetworkPolicy
使用场景:Pod网络策略、网络安全控制
# networkpolicy-example.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:name: api-allow-frontendnamespace: production
spec:podSelector:matchLabels:app: apipolicyTypes:- Ingressingress:- from:- podSelector:matchLabels:app: frontend- namespaceSelector:matchLabels:name: monitoringports:- protocol: TCPport: 8080
九、自定义资源 (Custom Resources)
1. CustomResourceDefinition (CRD)
使用场景:扩展Kubernetes API
# crd-example.yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:name: databases.example.com
spec:group: example.comversions:- name: v1served: truestorage: trueschema:openAPIV3Schema:type: objectproperties:spec:type: objectproperties:databaseName:type: stringversion:type: stringreplicas:type: integerscope: Namespacednames:plural: databasessingular: databasekind: DatabaseshortNames:- db
2. 自定义资源实例
# custom-resource-example.yaml
apiVersion: "example.com/v1"
kind: Database
metadata:name: my-postgres-db
spec:databaseName: "production-db"version: "13.2"replicas: 3
十、其他重要资源
1. PodDisruptionBudget
使用场景:维护应用可用性,优雅驱逐Pod
# pdb-example.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:name: web-pdb
spec:minAvailable: 2 # 或 maxUnavailable: 1selector:matchLabels:app: web
2. PriorityClass
使用场景:Pod调度优先级
# priorityclass-example.yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:name: high-priority
value: 1000000
globalDefault: false
description: "用于关键业务Pod"
3. RuntimeClass
使用场景:选择容器运行时
# runtimeclass-example.yaml
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:name: gvisor
handler: runsc # 容器运行时处理器
十一、资源类型速查表
| 资源类型 | API版本 | 主要用途 | 使用场景 |
|---|---|---|---|
| Pod | v1 | 最小部署单元 | 单容器/多容器应用 |
| Deployment | apps/v1 | 无状态应用部署 | Web服务、API服务 |
| StatefulSet | apps/v1 | 有状态应用 | 数据库、消息队列 |
| DaemonSet | apps/v1 | 节点级别部署 | 日志收集、监控代理 |
| Job | batch/v1 | 一次性任务 | 数据处理、批处理 |
| CronJob | batch/v1 | 定时任务 | 备份、报表生成 |
| Service | v1 | 服务发现 | 负载均衡、服务暴露 |
| Ingress | networking.k8s.io/v1 | HTTP路由 | 域名路由、SSL终止 |
| ConfigMap | v1 | 配置管理 | 应用配置、环境变量 |
| Secret | v1 | 敏感信息 | 密码、密钥、令牌 |
| PersistentVolume | v1 | 存储资源 | 持久化存储 |
| PersistentVolumeClaim | v1 | 存储请求 | 动态存储分配 |
| ServiceAccount | v1 | 身份认证 | Pod API访问 |
| Role/RoleBinding | rbac.authorization.k8s.io/v1 | 权限控制 | 命名空间权限 |
| Namespace | v1 | 资源隔离 | 多租户环境 |
| ResourceQuota | v1 | 资源限制 | 配额管理 |
| HPA | autoscaling/v2 | 自动扩缩容 | 基于指标自动调整 |
| NetworkPolicy | networking.k8s.io/v1 | 网络策略 | 网络安全控制 |
十二、最佳实践总结
-
工作负载选择:
- 无状态应用:使用 Deployment
- 有状态应用:使用 StatefulSet
- 节点级别服务:使用 DaemonSet
- 批处理任务:使用 Job/CronJob
-
存储策略:
- 临时数据:使用 emptyDir
- 持久化数据:使用 PVC + StorageClass
- 敏感配置:使用 Secret
- 普通配置:使用 ConfigMap
-
安全实践:
- 最小权限原则:使用 RBAC
- 网络隔离:使用 NetworkPolicy
- 资源限制:使用 ResourceQuota + LimitRange
-
高可用性:
- 多副本部署:使用 HPA 自动扩缩容
- 优雅终止:使用 PDB 保证可用性
- 健康检查:配置 liveness/readiness probes
通过合理组合这些资源类型,可以构建出生产级可用的 Kubernetes 应用架构。
