CodingDevOpsAdvanced45 minSaves 1 hour

Kubernetes Production Manifests for Stateless APIs

Platform engineers running EKS/GKE: Generate production-ready Kubernetes manifests for stateless APIs. Includes Deployment, HPA, and PDB for robust, scalable deployments.

Generate comprehensive Kubernetes YAML manifests for a stateless API, including Deployment, HPA, PDB, and Service. Platform engineers can create production-grade configurations for EKS/GKE, ensuring resilience and scalability through GitOps-friendly output.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
As a senior Kubernetes platform engineer, your role is to define robust infrastructure-as-code.

Context:
I require production-grade Kubernetes manifests for a new stateless API service. This API will run on either EKS or GKE clusters and must adhere to GitOps principles, meaning all configurations should be declarative and version-controlled. Security, scalability, and resilience are paramount.

Task:
Generate a complete set of Kubernetes YAML manifests for a stateless API. Include a Deployment, Horizontal Pod Autoscaler (HPA), Pod Disruption Budget (PDB), and a ClusterIP Service.
Additionally, provide guidance on how these manifests would integrate into a Helm chart or Kustomize overlay, and outline a clear rollout and rollback strategy for the service.

Constraints:
1.  **Manifests:**
    *   **Deployment:**
        *   Use `apps/v1` API version.
        *   Include appropriate resource `requests` and `limits` for CPU and memory.
        *   Define `readinessProbe` and `livenessProbe` with reasonable initial delays and intervals.
        *   Implement anti-affinity rules to spread pods across nodes for high availability.
        *   Utilize a `PodSecurityContext` and `ContainerSecurityContext` for hardening, avoiding `privileged` mode and `root` user where possible.
        *   Define `terminationGracePeriodSeconds`.
        *   Use `RollingUpdate` strategy.
    *   **Horizontal Pod Autoscaler (HPA):**
        *   Target `cpu_utilization_percentage`.
        *   Define `min_replicas` and `max_replicas`.
        *   Use `autoscaling/v2` API version.
    *   **Pod Disruption Budget (PDB):
        *   Define `minAvailable` or `maxUnavailable` to ensure service availability during voluntary disruptions.
    *   **Service:**
        *   Use `v1` API version with `ClusterIP` type.
        *   Map container `{{port}}` to service `port`.
    *   All manifests should be in a single YAML file, separated by `---`.
2.  **Placeholders:** Use clear placeholders for dynamic values like `{{api_name}}`, `{{container_image}}`, `{{namespace}}`, `{{cpu_request_m}}`, `{{memory_request_mib}}`, `{{min_replicas}}`, `{{max_replicas}}`, `{{target_cpu_utilization}}`, and `{{port}}`.
3.  **GitOps Integration:** Briefly explain how these manifests would be structured within a Helm chart or Kustomize setup for environment-specific customizations.
4.  **Rollout/Rollback Strategy:** Detail a safe rollout strategy for new versions, including health checks and canary/blue-green considerations. Also, describe a robust rollback procedure in case of issues.
5.  **Security:** Ensure all manifests reflect security best practices for production Kubernetes deployments.

Output:
1.  A single YAML block containing all Kubernetes manifests.
2.  A section providing Helm/Kustomize integration notes.
3.  A section detailing the rollout and rollback strategy.

Estimated results

DifficultyAdvanced
Setup time45 min
Time saved1 hour
Best modelsClaude, ChatGPT, Gemini
Best audienceCloud Computing, Software Development

Editor's note

Why this prompt matters

Deploying stateless APIs into production Kubernetes environments like EKS or GKE demands more than a basic kubectl apply. Platform engineers face the constant challenge of crafting manifests that are not only functional but also secure, scalable, and resilient. Manually configuring resource requests and limits, readiness/liveness probes, anti-affinity rules, and strong security contexts is a detail-intensive process, prone to inconsistencies and operational debt if not handled systematically. The goal is always a stable, performant service that can withstand disruptions and scale with demand, all while adhering to strict operational standards.

This workflow provides a structured approach to generate production-ready Kubernetes manifests tailored for stateless APIs. It ensures essential components like Deployments, Horizontal Pod Autoscalers (HPA) for elastic scaling, and Pod Disruption Budgets (PDB) for maintaining availability during cluster maintenance are correctly defined. By incorporating security best practices such as PodSecurityContext and ContainerSecurityContext and defining explicit resource requirements, this approach helps mitigate common operational risks from the outset.

For platform teams committed to GitOps, this method delivers declarative, version-controlled infrastructure definitions. It streamlines the creation of consistent configurations across environments, minimizing manual errors and accelerating deployment cycles. The focus on well-defined manifests also simplifies integration into Helm charts or Kustomize overlays, enabling predictable rollouts and efficient rollback strategies, which are critical for maintaining the integrity and stability of production services.

Anatomy

Prompt engineering breakdown

Role

As a senior Kubernetes platform engineer, your role is to define robust infrastructure-as-code.

Context

I require production-grade Kubernetes manifests for a new stateless API service. This API will run on either EKS or GKE clusters and must adhere to GitOps principles, meaning all configurations should be declarative and version-controlled. Security, scalability, and resilience are paramount.

Goal

Generate a complete set of Kubernetes YAML manifests for a stateless API. Include a Deployment, Horizontal Pod Autoscaler (HPA), Pod Disruption Budget (PDB), and a ClusterIP Service. Additionally, provide guidance on how these manifests would integrate into a Helm chart or Kustomize overlay, and outline a clear rollout and rollback strategy for the service.

Constraints

Manifests: Deployment (apps/v1, resource requests/limits, probes, anti-affinity, PodSecurityContext, ContainerSecurityContext, terminationGracePeriodSeconds, RollingUpdate), HPA (cpu_utilization_percentage, min/max_replicas, autoscaling/v2), PDB (minAvailable/maxUnavailable), Service (v1, ClusterIP, port mapping). All in a single YAML. Placeholders: {{api_name}}, {{container_image}}, etc. GitOps Integration: Brief explanation for Helm/Kustomize. Rollout/Rollback Strategy: Detail safe rollout (health checks, canary/blue-green) and robust rollback. Security: Best practices.

Output format

1. A single YAML block containing all Kubernetes manifests. 2. A section providing Helm/Kustomize integration notes. 3. A section detailing the rollout and rollback strategy.

Why this structure works

The prompt uses role priming to establish the AI's persona as a senior platform engineer, which guides the tone and technical depth of the response. Explicit constraints for each Kubernetes resource ensure that the generated manifests meet specific production-grade and security requirements. Finally, a structured output format clearly separates the YAML from the strategic guidance, making the response immediately usable and easy to parse.

Pick your version

Prompt variations

BeginnerWorks with any model

For those new to Kubernetes or needing basic production manifests with clear guidance on essential components.

prompt.txt
As a Kubernetes assistant, generate a set of production-ready manifests for a stateless API. Include a Deployment, Horizontal Pod Autoscaler (HPA), Pod Disruption Budget (PDB), and a ClusterIP Service. Provide these as a single YAML file. Also, explain how to use these with Helm or Kustomize and describe how to safely update and revert changes.
Ensure the Deployment has health checks and resource requests. The HPA should scale based on CPU. The PDB should prevent too many pods from going down. Use placeholders like `{{app_name}}`, `{{image_tag}}`, `{{cpu_limit}}`, `{{memory_limit}}`, and `{{service_port}}` for configurable values. Focus on clear, understandable YAML and practical advice for deployment.
ProfessionalBest with claude

When requiring detailed, production-grade Kubernetes manifests and strategic guidance, matching the original prompt's comprehensive scope.

prompt.txt
Assume the role of a senior Kubernetes platform engineer tasked with defining infrastructure-as-code for a stateless API. Your output must be production-ready Kubernetes manifests designed for EKS/GKE, adhering to GitOps principles, with paramount focus on security, scalability, and resilience.
Construct a complete set of YAML manifests: a Deployment (apps/v1, resource requests/limits, readiness/liveness probes, anti-affinity, `PodSecurityContext`, `ContainerSecurityContext`, `terminationGracePeriodSeconds`, `RollingUpdate`), an HPA (autoscaling/v2, CPU utilization target, min/max replicas), a PDB (`minAvailable`/`maxUnavailable`), and a ClusterIP Service (v1, `{{port}}` mapping).
Consolidate all manifests into a single YAML block. Additionally, explain how these integrate with Helm or Kustomize for environment-specific configurations, and detail a robust rollout/rollback strategy covering health checks, canary/blue-green, and recovery procedures. Use placeholders: `{{api_name}}`, `{{container_image}}`, `{{namespace}}`, `{{cpu_request_m}}`, `{{memory_request_mib}}`, `{{min_replicas}}`, `{{max_replicas}}`, `{{target_cpu_utilization}}`, `{{port}}`.
Short VersionWorks with any model

For a quick generation of core Kubernetes manifests for a stateless API, without extensive detail on constraints or strategies.

prompt.txt
Generate production-grade Kubernetes YAML for a stateless API. Include a Deployment with resource limits and probes, an HPA for CPU scaling, a PDB for disruption management, and a ClusterIP Service. Output all manifests in a single YAML. Briefly note how to integrate with Helm/Kustomize and provide a basic rollout/rollback plan. Use placeholders for `{{app_name}}`, `{{image}}`, `{{cpu_req}}`, `{{mem_req}}`, `{{min_rep}}`, `{{max_rep}}`, `{{cpu_target}}`, and `{{svc_port}}` to ensure flexibility for different deployments.
EnterpriseBest with claude

When the deployment requires consideration of compliance, auditing, cross-functional stakeholder review, and formal risk mitigation.

prompt.txt
As a lead platform architect, generate a comprehensive set of Kubernetes manifests and operational guidelines for a critical stateless API, adhering to enterprise-level governance and security policies. The deployment must support EKS/GKE environments, integrate with existing GitOps workflows, and ensure auditability.
Provide full YAML manifests for a Deployment (including advanced `securityContext` settings, anti-affinity, `RollingUpdate`, `terminationGracePeriodSeconds`), an HPA (v2, multi-metric potential, `min`/`max_replicas`), a PDB (`minAvailable`/`maxUnavailable`), and a ClusterIP Service, all in one file.
Alongside the manifests, detail Helm/Kustomize integration for compliance-driven environment segregation. Crucially, outline a formal rollout and rollback strategy, emphasizing change management protocols, stakeholder communication, and post-deployment validation steps. Incorporate placeholders like `{{service_id}}`, `{{docker_image}}`, `{{env_namespace}}`, `{{cpu_milicores}}`, `{{memory_megabytes}}`, `{{initial_replicas}}`, `{{peak_replicas}}`, `{{target_cpu_percentage}}`, `{{api_port}}`.

What you'll get

Expected output

``yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{api_name}} namespace: {{namespace}} labels: app: {{api_name}} spec: replicas: {{min_replicas}} selector: matchLabels: app: {{api_name}} strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 25% maxSurge: 25% template: metadata: labels: app: {{api_name}} spec: terminationGracePeriodSeconds: 30 securityContext: runAsNonRoot: true runAsUser: 10001 fsGroup: 10001 affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchLabels: app: {{api_name}} topologyKey: kubernetes.io/hostname containers: - name: {{api_name}} image: {{container_image}} ports: - containerPort: {{port}} name: http resources: requests: cpu: "{{cpu_request_m}}m" memory: "{{memory_request_mib}}Mi" limits: cpu: "{{cpu_request_m}}m" memory: "{{memory_request_mib}}Mi" livenessProbe: httpGet: path: /healthz port: http initialDelaySeconds: 15 periodSeconds: 20 timeoutSeconds: 5 failureThreshold: 3 readinessProbe: httpGet: path: /ready port: http initialDelaySeconds: 5 periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL --- apiVersion: v1 kind: Service metadata: name: {{api_name}} namespace: {{namespace}} labels: app: {{api_name}} spec: selector: app: {{api_name}} ports: - protocol: TCP port: {{port}} targetPort: http type: ClusterIP --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: {{api_name}}-hpa namespace: {{namespace}} spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: {{api_name}} minReplicas: {{min_replicas}} maxReplicas: {{max_replicas}} metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: {{target_cpu_utilization}} --- apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: {{api_name}}-pdb namespace: {{namespace}} labels: app: {{api_name}} spec: minAvailable: 1 selector: matchLabels: app: {{api_name}} ``

GitOps Integration:

For Helm, these manifests would reside in the templates/ directory of a chart. Dynamic values like api_name, container_image, resource requests, and replica counts would be templated using {{ .Values.key }}. The values.yaml file would define defaults, with environment-specific overrides managed via dedicated values-{{env}}.yaml files or --set flags during deployment. With Kustomize, these manifests form the base/ configuration. Overlays for different environments (e.g., dev/, prod/) would then patch the base. For instance, a prod/kustomization.yaml could adjust replica counts, image tags, or resource limits using patches or replicas fields, keeping the base configuration clean and reusable across environments.

Rollout/Rollback Strategy:

The RollingUpdate strategy in the Deployment ensures new pods are brought online and become ready before older pods are terminated, maintaining service availability during updates. The Pod Disruption Budget (PDB) further protects against voluntary disruptions, ensuring a minimum number of pods remain available. During a rollout, continuous monitoring of pod readiness, error rates, and latency is critical. If issues are detected, a rollback is initiated by reverting the container_image tag in the Deployment manifest to a known stable version and reapplying the configuration. Kubernetes' RollingUpdate handles the transition back. For urgent rollbacks, kubectl rollout undo deployment/{{api_name}} can quickly revert to the previous revision. Post-rollback, re-validation through monitoring confirms service stability.

Under the hood

Why this prompt works

This prompt succeeds by employing highly specific instructions and a clear role definition. Establishing the AI's persona as a "senior Kubernetes platform engineer" immediately sets the expectation for expert-level output, aligning with the target audience.

The prompt’s effectiveness stems from its granular constraints. Rather than general requests, it specifies exact Kubernetes API versions (apps/v1, autoscaling/v2, v1), required fields (e.g., readinessProbe, livenessProbe, PodSecurityContext), and desired values or strategies (RollingUpdate, anti-affinity rules, cpu_utilization_percentage). This level of detail eliminates ambiguity, guiding the model to generate production-ready YAML that adheres to industry best practices for scalability, resilience, and security.

Crucially, the explicit directives for PodSecurityContext and ContainerSecurityContext ensure security hardening is baked into the solution, a key concern for platform engineers. The instruction to use specific placeholders makes the output immediately templatable for GitOps workflows, enhancing its practical utility. Finally, requesting guidance on Helm/Kustomize integration and rollout strategies extends the prompt beyond mere code generation, prompting operational advice vital for deployment in EKS/GKE environments. This comprehensive approach ensures the generated content is not only technically correct but also operationally relevant.

Model fit

Best AI models for this prompt

Claude

Claude models excel at handling complex, multi-part requests and maintaining context across detailed specifications. Its ability to generate well-structured YAML and adhere to specific security and best-practice constraints makes it suitable for this task. It often produces clean, readable code that requires minimal post-editing. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT models are effective for generating structured code like Kubernetes manifests, especially when provided with clear, detailed constraints. It can accurately interpret the requirements for Deployment, HPA, PDB, and Service, and often generates sensible defaults for probes and resource requests. Verification of security contexts and specific anti-affinity rules is always recommended. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini models are capable of generating boilerplate code and configurations based on explicit instructions. When provided with a precise schema for Kubernetes objects, Gemini can construct the YAML with reasonable accuracy. For this prompt, ensure all security and best-practice constraints are clearly articulated to guide its output effectively. See the full Gemini hub for deeper guidance.

When to use

  • Deploying new stateless microservices that require production-grade reliability.
  • Establishing consistent Kubernetes configurations across multiple environments using GitOps principles.
  • Automating application scaling based on CPU utilization to handle varying loads.
  • Ensuring application availability during planned node maintenance or voluntary disruptions.
  • Migrating existing stateless APIs to Kubernetes, aiming for security and resilience.

When not to use

  • For stateful applications that require persistent storage or specific StatefulSet configurations.
  • If your service needs direct external exposure via a LoadBalancer or NodePort, as this setup specifies ClusterIP.
  • When a custom HPA metric beyond CPU utilization is required (e.g., QPS, custom Prometheus metrics).
  • For local development or non-production test environments where the overhead of PDBs or complex probes is unnecessary.

Get more from it

Pro tips

  • 1

    Regularly review resource `requests` and `limits` to prevent over-provisioning or `OOMKills` for your specific workload.

  • 2

    Test `readinessProbe` and `livenessProbe` thoroughly in staging to avoid false positives or unnecessary restarts.

  • 3

    Validate anti-affinity rules on multi-node clusters to ensure proper pod distribution and high availability.

  • 4

    Implement a robust GitOps pipeline to ensure consistent deployments and prevent configuration drift across environments.

  • 5

    Start with conservative HPA values, then tune `target_cpu_utilization` and `min`/`max_replicas` based on observed load patterns.

  • 6

    Consider `PodSecurityAdmission` (or `PodSecurityPolicies` in older clusters) for cluster-wide security enforcement, beyond just manifest settings.

Don't ship this

Common mistakes

  • Inadequate `terminationGracePeriodSeconds` leading to abrupt pod shutdowns and data loss for in-flight requests.

    Fix — Set a value allowing enough time for graceful application shutdown, matching its typical termination duration.

  • Overly aggressive HPA `target_cpu_utilization` causing thrashing or rapid scaling up and down.

    Fix — Begin with higher targets (e.g., 70-80%) and observe actual load patterns before fine-tuning for responsiveness.

  • Missing or incorrect `readinessProbe` leading to traffic redirection to unready pods, causing service errors.

    Fix — Ensure the readiness probe accurately reflects the application's ability to serve requests before accepting traffic.

  • Generic `PodSecurityContext` settings not aligned with specific application needs, potentially over-restricting or under-restricting.

    Fix — Customize security contexts to restrict only necessary capabilities and users, following the principle of least privilege.

  • Hardcoding values directly into manifests instead of using placeholders or templating, hindering reusability.

    Fix — Always use the provided placeholders for `{{api_name}}`, `{{namespace}}`, etc., for GitOps and environment-specific customization.

  • Not having a PDB, leading to service disruption during voluntary node drains or cluster upgrades.

    Fix — Always include a PDB with `minAvailable` or `maxUnavailable` to maintain quorum and service availability.

People also ask

Frequently asked questions

Q.Can this manifest set be used for internal services only?

Yes, the ClusterIP Service type is designed for internal communication within the Kubernetes cluster. It's suitable for backend APIs not directly exposed to external clients, relying on an Ingress or other service for external access.

Q.How do I handle different environments like dev, staging, and production?

The prompt output includes guidance for Helm charts or Kustomize. Use these tools to manage environment-specific values, such as image tags, resource requests, or HPA replica counts, through value files or overlays.

Q.Is it safe to deploy this directly to a production cluster?

These manifests provide a solid, secure baseline. However, always review and customize placeholders, resource requests, limits, and security contexts to match your specific application and organizational security policies before production deployment.

Q.What if my API needs external access?

This setup uses a ClusterIP Service for internal access. For external exposure, you would typically add an Ingress resource or a LoadBalancer Service, routing traffic to this ClusterIP Service.

Q.How do I monitor the HPA's effectiveness?

Monitor the HPA's scaling behavior and the application's performance metrics (CPU, memory, request latency) using your cluster's monitoring stack (e.g., Prometheus, Grafana). Adjust target_cpu_utilization, min_replicas, and max_replicas based on observed patterns.

Q.Does this account for database connections or external dependencies?

The manifests define the API service's deployment and scaling within Kubernetes. While it doesn't directly configure external dependencies like databases, it provides a stable platform for your API to connect to them, assuming network reachability.

Version 1.0Last reviewed July 20, 2026
Reviewed by PromptInFlow Editorial Team