1. Kubernetes清单文件基础认知
Kubernetes清单文件(Manifest)是定义集群工作负载的核心配置文件,采用YAML或JSON格式编写。这份看似简单的文本文件实际上承载着Kubernetes声明式API的全部精髓——你只需要告诉系统"想要什么状态",而不是"如何达到这个状态"。
清单文件通常包含以下几个关键部分:
- apiVersion:标识API的版本(如apps/v1)
- kind:资源类型(如Deployment、Service)
- metadata:名称、标签等元信息
- spec:期望状态的详细规格
- status(由系统自动生成):当前实际状态
一个典型的Deployment清单文件示例:
apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80注意:YAML对缩进极其敏感,建议使用2个空格(而非Tab)进行缩进,这是Kubernetes社区的通用约定。
2. 清单文件创建全流程详解
2.1 环境准备与工具链配置
在开始编写清单文件前,需要确保具备以下环境:
- 已安装kubectl命令行工具(版本需与集群版本兼容)
- 配置正确的kubeconfig文件(通常位于~/.kube/config)
- 安装yamllint或VS Code的YAML扩展用于语法检查
验证环境配置:
kubectl version --short kubectl config current-context2.2 资源类型选择策略
Kubernetes提供多种资源类型,常见选择包括:
| 资源类型 | 适用场景 | 典型组合 |
|---|---|---|
| Deployment | 无状态应用部署 | 配合Service暴露服务 |
| StatefulSet | 有状态应用(如数据库) | 配合PVC提供持久化存储 |
| DaemonSet | 每个节点运行一个Pod(如日志收集) | 直接使用Host网络或存储 |
| Job/CronJob | 批处理任务 | 独立运行或定时触发 |
选择原则:
- 优先使用Deployment(满足大多数场景)
- 需要稳定网络标识时用StatefulSet
- 节点级任务使用DaemonSet
- 临时任务使用Job/CronJob
2.3 清单文件编写实战
以部署一个高可用Web应用为例,我们需要创建以下资源:
- Deployment(应用部署)
apiVersion: apps/v1 kind: Deployment metadata: name: webapp spec: replicas: 3 strategy: rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: webapp template: metadata: labels: app: webapp spec: containers: - name: web image: myrepo/webapp:v1.2.0 ports: - containerPort: 8080 resources: requests: cpu: "100m" memory: "128Mi" limits: cpu: "500m" memory: "512Mi" livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 30 periodSeconds: 10- Service(服务暴露)
apiVersion: v1 kind: Service metadata: name: webapp-service spec: selector: app: webapp ports: - protocol: TCP port: 80 targetPort: 8080 type: LoadBalancer- HorizontalPodAutoscaler(自动扩缩容)
apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: webapp-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: webapp minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 502.4 清单文件校验与部署
在应用清单文件前,建议执行以下验证步骤:
- 语法检查
kubectl apply --dry-run=client -f deployment.yaml- 资源验证
kubectl get pods -l app=webapp kubectl describe svc webapp-service- 实时日志监控
kubectl logs -f deployment/webapp3. 高级配置与优化技巧
3.1 多环境配置管理
实际项目中通常需要区分开发、测试、生产环境,推荐以下方案:
- 使用Kustomize进行配置覆盖
base/ deployment.yaml kustomization.yaml overlays/ dev/ kustomization.yaml replica_count.yaml prod/ kustomization.yaml resource_limits.yaml- 通过Helm模板化配置
# values.yaml replicaCount: 1 image: repository: nginx tag: stable resources: limits: cpu: 100m memory: 128Mi3.2 安全加固配置
- 使用SecurityContext限制权限
securityContext: runAsNonRoot: true runAsUser: 1000 capabilities: drop: - ALL readOnlyRootFilesystem: true- 配置NetworkPolicy网络隔离
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny spec: podSelector: {} policyTypes: - Ingress - Egress3.3 性能优化实践
- 合理设置资源请求与限制
resources: requests: cpu: "100m" memory: "128Mi" limits: cpu: "500m" memory: "512Mi"- 配置拓扑分布约束(Topology Spread Constraints)
topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: ScheduleAnyway labelSelector: matchLabels: app: webapp4. 常见问题排查指南
4.1 镜像拉取失败问题
典型错误现象:
Failed to pull image "private.repo/image:v1": rpc error: code = Unknown desc = failed to pull and unpack image...排查步骤:
- 检查镜像地址是否正确
- 验证镜像拉取密钥是否存在
kubectl get secrets - 手动测试镜像拉取
docker pull private.repo/image:v1
4.2 Pod处于Pending状态
可能原因及解决方案:
| 现象 | 可能原因 | 解决方案 |
|---|---|---|
| 0/3 nodes are available | 资源不足 | 增加节点或调整资源请求 |
| pod has unbound PVC | 存储卷未就绪 | 检查StorageClass和PVC状态 |
| node(s) didn't match selector | 节点选择器不匹配 | 调整nodeSelector或节点标签 |
诊断命令:
kubectl describe pod <pod-name> kubectl get events --sort-by=.metadata.creationTimestamp4.3 ConfigMap权限问题
当遇到脚本执行权限问题时(如标题提到的configmap permission denied),解决方案:
- 确保脚本具有可执行权限
chmod +x script.sh- 通过initContainer设置权限
initContainers: - name: set-permissions image: busybox command: ["chmod", "+x", "/path/to/script.sh"] volumeMounts: - name: config-volume mountPath: /path/to- 或者直接使用ConfigMap的subPath挂载
volumeMounts: - name: config-volume mountPath: /script.sh subPath: script.sh