Kubernetes 资源类型大全:使用场景与配置示例
- [Kubernetes 资源类型大全:使用场景与配置示例](#Kubernetes 资源类型大全:使用场景与配置示例)
-
- 一、核心资源类型概览
- [二、工作负载资源(Workload Resources)](#二、工作负载资源(Workload Resources))
-
- [1. Pod](#1. Pod)
- [2. Deployment](#2. Deployment)
- [3. StatefulSet](#3. StatefulSet)
- [4. DaemonSet](#4. DaemonSet)
- [5. Job](#5. Job)
- [6. CronJob](#6. CronJob)
- [7. ReplicaSet](#7. ReplicaSet)
- 三、服务发现与负载均衡资源
-
- [1. Service](#1. Service)
- [2. Ingress](#2. Ingress)
- [3. Endpoints/EndpointSlice](#3. Endpoints/EndpointSlice)
- 四、配置资源
-
- [1. ConfigMap](#1. ConfigMap)
- [2. Secret](#2. Secret)
- 五、存储资源
-
- [1. PersistentVolume (PV)](#1. PersistentVolume (PV))
- [2. PersistentVolumeClaim (PVC)](#2. PersistentVolumeClaim (PVC))
- [3. StorageClass](#3. StorageClass)
- 六、安全资源
-
- [1. ServiceAccount](#1. ServiceAccount)
- [2. Role / ClusterRole](#2. Role / ClusterRole)
- [3. RoleBinding / ClusterRoleBinding](#3. RoleBinding / ClusterRoleBinding)
- 七、集群资源
-
- [1. Namespace](#1. Namespace)
- [2. ResourceQuota](#2. ResourceQuota)
- [3. LimitRange](#3. LimitRange)
- 八、扩展资源
-
- [1. HorizontalPodAutoscaler (HPA)](#1. HorizontalPodAutoscaler (HPA))
- [2. VerticalPodAutoscaler (VPA)](#2. VerticalPodAutoscaler (VPA))
- [3. NetworkPolicy](#3. NetworkPolicy)
- 九、自定义资源 (Custom Resources)
-
- [1. CustomResourceDefinition (CRD)](#1. CustomResourceDefinition (CRD))
- [2. 自定义资源实例](#2. 自定义资源实例)
- 十、其他重要资源
-
- [1. PodDisruptionBudget](#1. PodDisruptionBudget)
- [2. PriorityClass](#2. PriorityClass)
- [3. RuntimeClass](#3. RuntimeClass)
- 十一、资源类型速查表
- 十二、最佳实践总结
Kubernetes 资源类型大全:使用场景与配置示例
一、核心资源类型概览
Kubernetes资源 工作负载资源 服务发现资源 配置资源 存储资源 安全资源 集群资源 扩展资源 Pod Deployment StatefulSet DaemonSet Job/CronJob ReplicaSet Service Ingress Endpoint ConfigMap Secret ResourceQuota PersistentVolume PersistentVolumeClaim StorageClass ServiceAccount Role/RoleBinding ClusterRole/ClusterRoleBinding Namespace Node CustomResourceDefinition HorizontalPodAutoscaler VerticalPodAutoscaler NetworkPolicy
二、工作负载资源(Workload Resources)
1. Pod
使用场景:最小部署单元,单容器或多容器应用
yaml
# pod-example.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
env:
- name: ENV_VAR
value: "production"
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
# 多容器示例
- name: log-collector
image: busybox
command: ['sh', '-c', 'tail -f /dev/null']
2. Deployment
使用场景:无状态应用部署,支持滚动更新、回滚
yaml
# deployment-example.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
labels:
app: web
spec:
replicas: 3
selector:
matchLabels:
app: web
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.21
ports:
- containerPort: 80
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 5
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
3. StatefulSet
使用场景:有状态应用,需要稳定网络标识、持久化存储
yaml
# statefulset-example.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
serviceName: "mysql"
replicas: 3
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:8.0
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-secret
key: password
volumeMounts:
- name: mysql-data
mountPath: /var/lib/mysql
volumeClaimTemplates:
- metadata:
name: mysql-data
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "fast-ssd"
resources:
requests:
storage: 20Gi
4. DaemonSet
使用场景:每个节点运行一个副本(日志收集、节点监控)
yaml
# daemonset-example.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluentd-logging
labels:
k8s-app: fluentd-logging
spec:
selector:
matchLabels:
name: fluentd-logging
template:
metadata:
labels:
name: fluentd-logging
spec:
tolerations:
- key: node-role.kubernetes.io/master
effect: NoSchedule
containers:
- name: fluentd
image: fluent/fluentd:v1.14
resources:
limits:
memory: 200Mi
requests:
cpu: 100m
memory: 200Mi
volumeMounts:
- name: varlog
mountPath: /var/log
- name: varlibdockercontainers
mountPath: /var/lib/docker/containers
readOnly: true
terminationGracePeriodSeconds: 30
volumes:
- name: varlog
hostPath:
path: /var/log
- name: varlibdockercontainers
hostPath:
path: /var/lib/docker/containers
5. Job
使用场景:一次性任务、批处理作业
yaml
# job-example.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: pi-calculation
spec:
completions: 5 # 需要完成5个Pod
parallelism: 2 # 同时运行2个Pod
backoffLimit: 4 # 重试次数
template:
spec:
containers:
- name: pi
image: perl:5.34
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
restartPolicy: Never
6. CronJob
使用场景:定时任务、周期性作业
yaml
# cronjob-example.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: database-backup
spec:
schedule: "0 2 * * *" # 每天凌晨2点
startingDeadlineSeconds: 200
concurrencyPolicy: Forbid # 禁止并发执行
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: postgres:13
command:
- /bin/sh
- -c
- pg_dump -h db-host -U postgres mydb > /backup/backup.sql
env:
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
volumeMounts:
- name: backup-volume
mountPath: /backup
volumes:
- name: backup-volume
persistentVolumeClaim:
claimName: backup-pvc
restartPolicy: OnFailure
7. ReplicaSet
使用场景:Pod副本管理(Deployment底层使用)
yaml
# replicaset-example.yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: frontend
labels:
app: guestbook
tier: frontend
spec:
replicas: 3
selector:
matchLabels:
tier: frontend
template:
metadata:
labels:
tier: frontend
spec:
containers:
- name: php-redis
image: gcr.io/google_samples/gb-frontend:v3
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: GET_HOSTS_FROM
value: dns
ports:
- containerPort: 80
三、服务发现与负载均衡资源
1. Service
使用场景:服务发现、负载均衡、网络访问抽象
yaml
# service-example.yaml
apiVersion: v1
kind: Service
metadata:
name: web-service
spec:
selector:
app: web
ports:
- name: http
port: 80
targetPort: 8080
protocol: TCP
- name: https
port: 443
targetPort: 8443
protocol: TCP
type: LoadBalancer # ClusterIP, NodePort, LoadBalancer
# 外部负载均衡器配置
externalTrafficPolicy: Local
loadBalancerIP: 192.168.1.100
2. Ingress
使用场景:HTTP/HTTPS路由、域名基于的路由、SSL终止
yaml
# ingress-example.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
tls:
- hosts:
- app.example.com
secretName: example-tls
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
- path: /api
pathType: Prefix
backend:
service:
name: api-service
port:
number: 8080
3. Endpoints/EndpointSlice
使用场景:手动配置服务端点
yaml
# endpoints-example.yaml
apiVersion: v1
kind: Endpoints
metadata:
name: external-service
subsets:
- addresses:
- ip: 192.168.1.100
- ip: 192.168.1.101
ports:
- port: 80
name: http
四、配置资源
1. ConfigMap
使用场景:配置数据存储、环境变量、配置文件
yaml
# 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=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
2. Secret
使用场景:敏感信息存储(密码、令牌、密钥)
yaml
# 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)
使用场景:集群范围的存储资源
yaml
# persistentvolume-example.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-volume
labels:
type: local
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: slow
hostPath:
path: "/mnt/data"
2. PersistentVolumeClaim (PVC)
使用场景:用户对存储的请求
yaml
# persistentvolumeclaim-example.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pv-claim
spec:
storageClassName: slow
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 3Gi
3. StorageClass
使用场景:动态卷配置、存储类别定义
yaml
# storageclass-example.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: fast-ssd
provisioner: kubernetes.io/gce-pd
parameters:
type: pd-ssd
replication-type: none
allowVolumeExpansion: true
mountOptions:
- discard
六、安全资源
1. ServiceAccount
使用场景:Pod身份认证、API访问控制
yaml
# serviceaccount-example.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: build-robot
namespace: default
secrets:
- name: build-robot-token-xyz
2. Role / ClusterRole
使用场景:命名空间/集群范围的权限定义
yaml
# role-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: 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
使用场景:角色绑定到主体
yaml
# rolebinding-example.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
- kind: User
name: jane
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
七、集群资源
1. Namespace
使用场景:资源隔离、多租户环境
yaml
# namespace-example.yaml
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
name: production
environment: prod
2. ResourceQuota
使用场景:资源配额限制
yaml
# resourcequota-example.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-resources
namespace: production
spec:
hard:
requests.cpu: "1"
requests.memory: 1Gi
limits.cpu: "2"
limits.memory: 2Gi
requests.storage: 10Gi
persistentvolumeclaims: "4"
services.loadbalancers: "2"
services.nodeports: "0"
3. LimitRange
使用场景:限制资源请求和限制的默认值
yaml
# limitrange-example.yaml
apiVersion: v1
kind: LimitRange
metadata:
name: mem-limit-range
namespace: production
spec:
limits:
- default:
memory: 512Mi
cpu: 500m
defaultRequest:
memory: 256Mi
cpu: 100m
type: Container
八、扩展资源
1. HorizontalPodAutoscaler (HPA)
使用场景:基于CPU/内存使用率自动扩缩容
yaml
# hpa-example.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
2. VerticalPodAutoscaler (VPA)
使用场景:自动调整Pod资源请求
yaml
# vpa-example.yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: web-app-vpa
spec:
targetRef:
apiVersion: "apps/v1"
kind: Deployment
name: web-app
updatePolicy:
updateMode: "Auto"
resourcePolicy:
containerPolicies:
- containerName: "*"
minAllowed:
cpu: 100m
memory: 50Mi
maxAllowed:
cpu: 1
memory: 1Gi
controlledResources: ["cpu", "memory"]
3. NetworkPolicy
使用场景:Pod网络策略、网络安全控制
yaml
# networkpolicy-example.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow-frontend
namespace: production
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
- namespaceSelector:
matchLabels:
name: monitoring
ports:
- protocol: TCP
port: 8080
九、自定义资源 (Custom Resources)
1. CustomResourceDefinition (CRD)
使用场景:扩展Kubernetes API
yaml
# crd-example.yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: databases.example.com
spec:
group: example.com
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
databaseName:
type: string
version:
type: string
replicas:
type: integer
scope: Namespaced
names:
plural: databases
singular: database
kind: Database
shortNames:
- db
2. 自定义资源实例
yaml
# 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
yaml
# pdb-example.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web-pdb
spec:
minAvailable: 2 # 或 maxUnavailable: 1
selector:
matchLabels:
app: web
2. PriorityClass
使用场景:Pod调度优先级
yaml
# priorityclass-example.yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: high-priority
value: 1000000
globalDefault: false
description: "用于关键业务Pod"
3. RuntimeClass
使用场景:选择容器运行时
yaml
# 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 应用架构。