在Kubernetes(K8s)中,一个完整的应用实例通常包括至少以下几个组成部分:
1.Deployment YAML:用于定义应用的副本集及其更新策略。Deployment确保Pod的数量始终符合期望的状态,并能在升级、回滚时保证应用的可用性。
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-deployment
labels:
app: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: myregistry/myapp:latest
ports:
- containerPort: 80
env:
- name: DATABASE_URL
value: mongodb://mongo-service.default.svc.cluster.local:27017/mydb
- name: SECRET_KEY
valueFrom:
secretKeyRef:
name: myapp-secrets
key: secret_key
imagePullPolicy: Always
2.Service YAML:用于定义访问Pod的方式,它可以提供负载均衡和服务发现的功能。定义服务发现机制和网络路由规则。
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP
3.ConfigMap YAML(可选):用于存储应用程序的非敏感配置数据。
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: myapp-configmap
data:
application.properties: |
property1=value1
property2=value2
4.Secret YAML(可选):用于存储敏感信息,如密码、密钥等。
# secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: myapp-secrets
type: Opaque
data:
secret_key: c2VjcmV0LWtleQ== # base64 编码的秘密值
5.PersistentVolumeClaim (PVC) YAML(可选):请求持久化的存储卷。对于有状态应用,可能会用到持久化存储。PVC声明所需的存储资源,PV是集群提供的存储资源。
# pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: myapp-data-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: standard
6.StatefulSet YAML(适用于有状态应用):定义具有稳定唯一标识符和有序网络标识的应用程序实例。
# statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: myapp-statefulset
spec:
serviceName: myapp-headless
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: myregistry/myapp:stable
volumeMounts:
- name: data-volume
mountPath: /var/app/data
volumeClaimTemplates:
- metadata:
name: data-volume
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
storageClassName: standard
每个YAML文件都是独立定义Kubernetes对象的,可以单独创建。通过kubectl工具将这些YAML文件应用到集群中:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f configmap.yaml
kubectl apply -f secret.yaml
kubectl apply -f pvc.yaml
kubectl apply -f statefulset.yaml