k8s-manifest-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kubernetes Manifest Generator

Kubernetes清单生成器

Step-by-step guidance for creating production-ready Kubernetes manifests including Deployments, Services, ConfigMaps, Secrets, and PersistentVolumeClaims.
创建可用于生产环境的Kubernetes清单的分步指南,包括Deployment、Service、ConfigMap、Secret和PersistentVolumeClaim。

Purpose

用途

This skill provides comprehensive guidance for generating well-structured, secure, and production-ready Kubernetes manifests following cloud-native best practices and Kubernetes conventions.
本技能提供全面指南,帮助您遵循云原生最佳实践和Kubernetes规范,生成结构合理、安全且可用于生产环境的Kubernetes清单。

When to Use This Skill

何时使用此技能

Use this skill when you need to:
  • Create new Kubernetes Deployment manifests
  • Define Service resources for network connectivity
  • Generate ConfigMap and Secret resources for configuration management
  • Create PersistentVolumeClaim manifests for stateful workloads
  • Follow Kubernetes best practices and naming conventions
  • Implement resource limits, health checks, and security contexts
  • Design manifests for multi-environment deployments
当您需要以下操作时,可使用此技能:
  • 创建新的Kubernetes Deployment清单
  • 定义用于网络连接的Service资源
  • 生成用于配置管理的ConfigMap和Secret资源
  • 为有状态工作负载创建PersistentVolumeClaim清单
  • 遵循Kubernetes最佳实践和命名规范
  • 实施资源限制、健康检查和安全上下文
  • 为多环境部署设计清单

Step-by-Step Workflow

分步工作流程

1. Gather Requirements

1. 收集需求

Understand the workload:
  • Application type (stateless/stateful)
  • Container image and version
  • Environment variables and configuration needs
  • Storage requirements
  • Network exposure requirements (internal/external)
  • Resource requirements (CPU, memory)
  • Scaling requirements
  • Health check endpoints
Questions to ask:
  • What is the application name and purpose?
  • What container image and tag will be used?
  • Does the application need persistent storage?
  • What ports does the application expose?
  • Are there any secrets or configuration files needed?
  • What are the CPU and memory requirements?
  • Does the application need to be exposed externally?
了解工作负载:
  • 应用类型(无状态/有状态)
  • 容器镜像和版本
  • 环境变量和配置需求
  • 存储需求
  • 网络暴露需求(内部/外部)
  • 资源需求(CPU、内存)
  • 扩容需求
  • 健康检查端点
需询问的问题:
  • 应用名称和用途是什么?
  • 将使用哪个容器镜像和标签?
  • 应用是否需要持久化存储?
  • 应用暴露哪些端口?
  • 是否需要任何密钥或配置文件?
  • CPU和内存需求是什么?
  • 应用是否需要对外暴露?

2. Create Deployment Manifest

2. 创建Deployment清单

Follow this structure:
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: <app-name>
  namespace: <namespace>
  labels:
    app: <app-name>
    version: <version>
spec:
  replicas: 3
  selector:
    matchLabels:
      app: <app-name>
  template:
    metadata:
      labels:
        app: <app-name>
        version: <version>
    spec:
      containers:
        - name: <container-name>
          image: <image>:<tag>
          ports:
            - containerPort: <port>
              name: http
          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "512Mi"
              cpu: "500m"
          livenessProbe:
            httpGet:
              path: /health
              port: http
            initialDelaySeconds: 30
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /ready
              port: http
            initialDelaySeconds: 5
            periodSeconds: 5
          env:
            - name: ENV_VAR
              value: "value"
          envFrom:
            - configMapRef:
                name: <app-name>-config
            - secretRef:
                name: <app-name>-secret
Best practices to apply:
  • Always set resource requests and limits
  • Implement both liveness and readiness probes
  • Use specific image tags (never
    :latest
    )
  • Apply security context for non-root users
  • Use labels for organization and selection
  • Set appropriate replica count based on availability needs
Reference: See
references/deployment-spec.md
for detailed deployment options
遵循以下结构:
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: <app-name>
  namespace: <namespace>
  labels:
    app: <app-name>
    version: <version>
spec:
  replicas: 3
  selector:
    matchLabels:
      app: <app-name>
  template:
    metadata:
      labels:
        app: <app-name>
        version: <version>
    spec:
      containers:
        - name: <container-name>
          image: <image>:<tag>
          ports:
            - containerPort: <port>
              name: http
          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "512Mi"
              cpu: "500m"
          livenessProbe:
            httpGet:
              path: /health
              port: http
            initialDelaySeconds: 30
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /ready
              port: http
            initialDelaySeconds: 5
            periodSeconds: 5
          env:
            - name: ENV_VAR
              value: "value"
          envFrom:
            - configMapRef:
                name: <app-name>-config
            - secretRef:
                name: <app-name>-secret
需遵循的最佳实践:
  • 始终设置资源请求和限制
  • 同时实现存活探针和就绪探针
  • 使用特定的镜像标签(切勿使用
    :latest
  • 为非root用户应用安全上下文
  • 使用标签进行组织和选择
  • 根据可用性需求设置合适的副本数量
参考: 有关详细的Deployment选项,请参阅
references/deployment-spec.md

3. Create Service Manifest

3. 创建Service清单

Choose the appropriate Service type:
ClusterIP (internal only):
yaml
apiVersion: v1
kind: Service
metadata:
  name: <app-name>
  namespace: <namespace>
  labels:
    app: <app-name>
spec:
  type: ClusterIP
  selector:
    app: <app-name>
  ports:
    - name: http
      port: 80
      targetPort: 8080
      protocol: TCP
LoadBalancer (external access):
yaml
apiVersion: v1
kind: Service
metadata:
  name: <app-name>
  namespace: <namespace>
  labels:
    app: <app-name>
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: nlb
spec:
  type: LoadBalancer
  selector:
    app: <app-name>
  ports:
    - name: http
      port: 80
      targetPort: 8080
      protocol: TCP
Reference: See
references/service-spec.md
for service types and networking
选择合适的Service类型:
ClusterIP(仅内部访问):
yaml
apiVersion: v1
kind: Service
metadata:
  name: <app-name>
  namespace: <namespace>
  labels:
    app: <app-name>
spec:
  type: ClusterIP
  selector:
    app: <app-name>
  ports:
    - name: http
      port: 80
      targetPort: 8080
      protocol: TCP
LoadBalancer(外部访问):
yaml
apiVersion: v1
kind: Service
metadata:
  name: <app-name>
  namespace: <namespace>
  labels:
    app: <app-name>
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: nlb
spec:
  type: LoadBalancer
  selector:
    app: <app-name>
  ports:
    - name: http
      port: 80
      targetPort: 8080
      protocol: TCP
参考: 有关Service类型和网络的详细信息,请参阅
references/service-spec.md

4. Create ConfigMap

4. 创建ConfigMap

For application configuration:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: <app-name>-config
  namespace: <namespace>
data:
  APP_MODE: production
  LOG_LEVEL: info
  DATABASE_HOST: db.example.com
  # For config files
  app.properties: |
    server.port=8080
    server.host=0.0.0.0
    logging.level=INFO
Best practices:
  • Use ConfigMaps for non-sensitive data only
  • Organize related configuration together
  • Use meaningful names for keys
  • Consider using one ConfigMap per component
  • Version ConfigMaps when making changes
Reference: See
assets/configmap-template.yaml
for examples
用于应用配置:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: <app-name>-config
  namespace: <namespace>
data:
  APP_MODE: production
  LOG_LEVEL: info
  DATABASE_HOST: db.example.com
  # For config files
  app.properties: |
    server.port=8080
    server.host=0.0.0.0
    logging.level=INFO
最佳实践:
  • 仅将ConfigMap用于非敏感数据
  • 将相关配置组织在一起
  • 为键使用有意义的名称
  • 考虑为每个组件使用一个ConfigMap
  • 更改时为ConfigMap设置版本
参考: 有关示例,请参阅
assets/configmap-template.yaml

5. Create Secret

5. 创建Secret

For sensitive data:
yaml
apiVersion: v1
kind: Secret
metadata:
  name: <app-name>-secret
  namespace: <namespace>
type: Opaque
stringData:
  DATABASE_PASSWORD: "changeme"
  API_KEY: "secret-api-key"
  # For certificate files
  tls.crt: |
    -----BEGIN CERTIFICATE-----
    ...
    -----END CERTIFICATE-----
  tls.key: |
    -----BEGIN PRIVATE KEY-----
    ...
    -----END PRIVATE KEY-----
Security considerations:
  • Never commit secrets to Git in plain text
  • Use Sealed Secrets, External Secrets Operator, or Vault
  • Rotate secrets regularly
  • Use RBAC to limit secret access
  • Consider using Secret type:
    kubernetes.io/tls
    for TLS secrets
用于敏感数据:
yaml
apiVersion: v1
kind: Secret
metadata:
  name: <app-name>-secret
  namespace: <namespace>
type: Opaque
stringData:
  DATABASE_PASSWORD: "changeme"
  API_KEY: "secret-api-key"
  # For certificate files
  tls.crt: |
    -----BEGIN CERTIFICATE-----
    ...
    -----END CERTIFICATE-----
  tls.key: |
    -----BEGIN PRIVATE KEY-----
    ...
    -----END PRIVATE KEY-----
安全注意事项:
  • 切勿以明文形式将密钥提交到Git
  • 使用Sealed Secrets、External Secrets Operator或Vault
  • 定期轮换密钥
  • 使用RBAC限制密钥访问
  • 对于TLS密钥,考虑使用Secret类型:
    kubernetes.io/tls

6. Create PersistentVolumeClaim (if needed)

6. 创建PersistentVolumeClaim(如有需要)

For stateful applications:
yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: <app-name>-data
  namespace: <namespace>
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: gp3
  resources:
    requests:
      storage: 10Gi
Mount in Deployment:
yaml
spec:
  template:
    spec:
      containers:
        - name: app
          volumeMounts:
            - name: data
              mountPath: /var/lib/app
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: <app-name>-data
Storage considerations:
  • Choose appropriate StorageClass for performance needs
  • Use ReadWriteOnce for single-pod access
  • Use ReadWriteMany for multi-pod shared storage
  • Consider backup strategies
  • Set appropriate retention policies
用于有状态应用:
yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: <app-name>-data
  namespace: <namespace>
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: gp3
  resources:
    requests:
      storage: 10Gi
在Deployment中挂载:
yaml
spec:
  template:
    spec:
      containers:
        - name: app
          volumeMounts:
            - name: data
              mountPath: /var/lib/app
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: <app-name>-data
存储注意事项:
  • 根据性能需求选择合适的StorageClass
  • 对单Pod访问使用ReadWriteOnce
  • 对多Pod共享存储使用ReadWriteMany
  • 考虑备份策略
  • 设置合适的保留策略

7. Apply Security Best Practices

7. 应用安全最佳实践

Add security context to Deployment:
yaml
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 1000
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: app
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
                - ALL
Security checklist:
  • Run as non-root user
  • Drop all capabilities
  • Use read-only root filesystem
  • Disable privilege escalation
  • Set seccomp profile
  • Use Pod Security Standards
为Deployment添加安全上下文:
yaml
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 1000
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: app
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop:
                - ALL
安全检查清单:
  • 以非root用户运行
  • 移除所有权限
  • 使用只读根文件系统
  • 禁用权限提升
  • 设置seccomp配置文件
  • 使用Pod安全标准

8. Add Labels and Annotations

8. 添加标签和注解

Standard labels (recommended):
yaml
metadata:
  labels:
    app.kubernetes.io/name: <app-name>
    app.kubernetes.io/instance: <instance-name>
    app.kubernetes.io/version: "1.0.0"
    app.kubernetes.io/component: backend
    app.kubernetes.io/part-of: <system-name>
    app.kubernetes.io/managed-by: kubectl
Useful annotations:
yaml
metadata:
  annotations:
    description: "Application description"
    contact: "team@example.com"
    prometheus.io/scrape: "true"
    prometheus.io/port: "9090"
    prometheus.io/path: "/metrics"
推荐的标准标签:
yaml
metadata:
  labels:
    app.kubernetes.io/name: <app-name>
    app.kubernetes.io/instance: <instance-name>
    app.kubernetes.io/version: "1.0.0"
    app.kubernetes.io/component: backend
    app.kubernetes.io/part-of: <system-name>
    app.kubernetes.io/managed-by: kubectl
有用的注解:
yaml
metadata:
  annotations:
    description: "Application description"
    contact: "team@example.com"
    prometheus.io/scrape: "true"
    prometheus.io/port: "9090"
    prometheus.io/path: "/metrics"

9. Organize Multi-Resource Manifests

9. 组织多资源清单

File organization options:
Option 1: Single file with
---
separator
yaml
undefined
文件组织选项:
选项1:使用
---
分隔符的单个文件
yaml
undefined

app-name.yaml

app-name.yaml


apiVersion: v1 kind: ConfigMap ...

apiVersion: v1 kind: Secret ...

apiVersion: apps/v1 kind: Deployment ...

apiVersion: v1 kind: Service ...

**Option 2: Separate files**
manifests/ ├── configmap.yaml ├── secret.yaml ├── deployment.yaml ├── service.yaml └── pvc.yaml

**Option 3: Kustomize structure**
base/ ├── kustomization.yaml ├── deployment.yaml ├── service.yaml └── configmap.yaml overlays/ ├── dev/ │ └── kustomization.yaml └── prod/ └── kustomization.yaml
undefined

apiVersion: v1 kind: ConfigMap ...

apiVersion: v1 kind: Secret ...

apiVersion: apps/v1 kind: Deployment ...

apiVersion: v1 kind: Service ...

**选项2:单独文件**
manifests/ ├── configmap.yaml ├── secret.yaml ├── deployment.yaml ├── service.yaml └── pvc.yaml

**选项3:Kustomize结构**
base/ ├── kustomization.yaml ├── deployment.yaml ├── service.yaml └── configmap.yaml overlays/ ├── dev/ │ └── kustomization.yaml └── prod/ └── kustomization.yaml
undefined

10. Validate and Test

10. 验证和测试

Validation steps:
bash
undefined
验证步骤:
bash
undefined

Dry-run validation

Dry-run validation

kubectl apply -f manifest.yaml --dry-run=client
kubectl apply -f manifest.yaml --dry-run=client

Server-side validation

Server-side validation

kubectl apply -f manifest.yaml --dry-run=server
kubectl apply -f manifest.yaml --dry-run=server

Validate with kubeval

Validate with kubeval

kubeval manifest.yaml
kubeval manifest.yaml

Validate with kube-score

Validate with kube-score

kube-score score manifest.yaml
kube-score score manifest.yaml

Check with kube-linter

Check with kube-linter

kube-linter lint manifest.yaml

**Testing checklist:**

- [ ] Manifest passes dry-run validation
- [ ] All required fields are present
- [ ] Resource limits are reasonable
- [ ] Health checks are configured
- [ ] Security context is set
- [ ] Labels follow conventions
- [ ] Namespace exists or is created
kube-linter lint manifest.yaml

**测试检查清单:**

- [ ] 清单通过dry-run验证
- [ ] 所有必填字段均已存在
- [ ] 资源限制合理
- [ ] 已配置健康检查
- [ ] 已设置安全上下文
- [ ] 标签遵循规范
- [ ] 命名空间已存在或已创建

Common Patterns

常见模式

Pattern 1: Simple Stateless Web Application

模式1:简单无状态Web应用

Use case: Standard web API or microservice
Components needed:
  • Deployment (3 replicas for HA)
  • ClusterIP Service
  • ConfigMap for configuration
  • Secret for API keys
  • HorizontalPodAutoscaler (optional)
Reference: See
assets/deployment-template.yaml
使用场景: 标准Web API或微服务
所需组件:
  • Deployment(3个副本以实现高可用)
  • ClusterIP Service
  • 用于配置的ConfigMap
  • 用于API密钥的Secret
  • HorizontalPodAutoscaler(可选)
参考: 请参阅
assets/deployment-template.yaml

Pattern 2: Stateful Database Application

模式2:有状态数据库应用

Use case: Database or persistent storage application
Components needed:
  • StatefulSet (not Deployment)
  • Headless Service
  • PersistentVolumeClaim template
  • ConfigMap for DB configuration
  • Secret for credentials
使用场景: 数据库或持久化存储应用
所需组件:
  • StatefulSet(而非Deployment)
  • Headless Service
  • PersistentVolumeClaim模板
  • 用于数据库配置的ConfigMap
  • 用于凭据的Secret

Pattern 3: Background Job or Cron

模式3:后台作业或定时任务

Use case: Scheduled tasks or batch processing
Components needed:
  • CronJob or Job
  • ConfigMap for job parameters
  • Secret for credentials
  • ServiceAccount with RBAC
使用场景: 计划任务或批处理
所需组件:
  • CronJob或Job
  • 用于作业参数的ConfigMap
  • 用于凭据的Secret
  • 带有RBAC的ServiceAccount

Pattern 4: Multi-Container Pod

模式4:多容器Pod

Use case: Application with sidecar containers
Components needed:
  • Deployment with multiple containers
  • Shared volumes between containers
  • Init containers for setup
  • Service (if needed)
使用场景: 包含边车容器的应用
所需组件:
  • 包含多个容器的Deployment
  • 容器之间的共享卷
  • 用于设置的Init容器
  • Service(如有需要)

Templates

模板

The following templates are available in the
assets/
directory:
  • deployment-template.yaml
    - Standard deployment with best practices
  • service-template.yaml
    - Service configurations (ClusterIP, LoadBalancer, NodePort)
  • configmap-template.yaml
    - ConfigMap examples with different data types
  • secret-template.yaml
    - Secret examples (to be generated, not committed)
  • pvc-template.yaml
    - PersistentVolumeClaim templates
assets/
目录中提供以下模板:
  • deployment-template.yaml
    - 包含最佳实践的标准Deployment模板
  • service-template.yaml
    - Service配置(ClusterIP、LoadBalancer、NodePort)
  • configmap-template.yaml
    - 包含不同数据类型的ConfigMap示例
  • secret-template.yaml
    - Secret示例(需生成,请勿提交)
  • pvc-template.yaml
    - PersistentVolumeClaim模板

Reference Documentation

参考文档

  • references/deployment-spec.md
    - Detailed Deployment specification
  • references/service-spec.md
    - Service types and networking details
  • references/deployment-spec.md
    - 详细的Deployment规范
  • references/service-spec.md
    - Service类型和网络细节

Best Practices Summary

最佳实践总结

  1. Always set resource requests and limits - Prevents resource starvation
  2. Implement health checks - Ensures Kubernetes can manage your application
  3. Use specific image tags - Avoid unpredictable deployments
  4. Apply security contexts - Run as non-root, drop capabilities
  5. Use ConfigMaps and Secrets - Separate config from code
  6. Label everything - Enables filtering and organization
  7. Follow naming conventions - Use standard Kubernetes labels
  8. Validate before applying - Use dry-run and validation tools
  9. Version your manifests - Keep in Git with version control
  10. Document with annotations - Add context for other developers
  1. 始终设置资源请求和限制 - 防止资源耗尽
  2. 实施健康检查 - 确保Kubernetes可以管理您的应用
  3. 使用特定的镜像标签 - 避免不可预测的部署
  4. 应用安全上下文 - 以非root用户运行,移除权限
  5. 使用ConfigMap和Secret - 将配置与代码分离
  6. 为所有资源添加标签 - 支持过滤和组织
  7. 遵循命名规范 - 使用标准Kubernetes标签
  8. 应用前验证 - 使用dry-run和验证工具
  9. 为清单设置版本 - 存储在Git中并进行版本控制
  10. 使用注解添加文档 - 为其他开发人员添加上下文

Troubleshooting

故障排除

Pods not starting:
  • Check image pull errors:
    kubectl describe pod <pod-name>
  • Verify resource availability:
    kubectl get nodes
  • Check events:
    kubectl get events --sort-by='.lastTimestamp'
Service not accessible:
  • Verify selector matches pod labels:
    kubectl get endpoints <service-name>
  • Check service type and port configuration
  • Test from within cluster:
    kubectl run debug --rm -it --image=busybox -- sh
ConfigMap/Secret not loading:
  • Verify names match in Deployment
  • Check namespace
  • Ensure resources exist:
    kubectl get configmap,secret
Pod无法启动:
  • 检查镜像拉取错误:
    kubectl describe pod <pod-name>
  • 验证资源可用性:
    kubectl get nodes
  • 检查事件:
    kubectl get events --sort-by='.lastTimestamp'
Service无法访问:
  • 验证选择器是否匹配Pod标签:
    kubectl get endpoints <service-name>
  • 检查Service类型和端口配置
  • 在集群内部测试:
    kubectl run debug --rm -it --image=busybox -- sh
ConfigMap/Secret未加载:
  • 验证Deployment中的名称是否匹配
  • 检查命名空间
  • 确保资源存在:
    kubectl get configmap,secret

Next Steps

后续步骤

After creating manifests:
  1. Store in Git repository
  2. Set up CI/CD pipeline for deployment
  3. Consider using Helm or Kustomize for templating
  4. Implement GitOps with ArgoCD or Flux
  5. Add monitoring and observability
创建清单后:
  1. 存储在Git仓库中
  2. 设置用于部署的CI/CD流水线
  3. 考虑使用Helm或Kustomize进行模板化
  4. 使用ArgoCD或Flux实施GitOps
  5. 添加监控和可观测性

Related Skills

相关技能

  • helm-chart-scaffolding
    - For templating and packaging
  • gitops-workflow
    - For automated deployments
  • k8s-security-policies
    - For advanced security configurations
  • helm-chart-scaffolding
    - 用于模板化和打包
  • gitops-workflow
    - 用于自动化部署
  • k8s-security-policies
    - 用于高级安全配置