Production-Ready Kubernetes YAML Templates (Ingress, PV, CronJobs) — From Basics to Advanced


☸️ Production-Ready Kubernetes YAML Templates (Ingress, PV, CronJobs) — From Basics to Advanced

Kubernetes is powerful. But without properly crafted YAML manifests, your deployments can be unstable, insecure, or unscalable in production.

In this blog, we’ll walk through battle-tested YAML templates for 3 production-critical resources:

  • 🔗 Ingress (for routing HTTP traffic)
  • 💾 Persistent Volume Claims (for data persistence)
  • ⏰ CronJobs (for scheduled automation)

Each section includes:

  • 🔍 Beginner-to-pro-level explanations
  • ✅ Templates that follow best practices
  • 🧠 Tips to avoid common misconfigurations

🔗 1. Ingress — Route Traffic Like a Pro

✅ What is Ingress?

Ingress manages external HTTP(S) access to services within your cluster. It’s like a traffic cop for your microservices.

Instead of exposing each service separately, you:

  • Define a single domain (e.g., app.example.com)
  • Route to the correct service based on path/hostname

📌 Requires an Ingress Controller like NGINX, Traefik, or AWS ALB.


🧾 Basic Ingress YAML

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: web-service
            port:
              number: 80

🔐 Production-Ready Ingress Features

  • ✅ TLS with HTTPS
  • ✅ Host/path routing
  • ✅ Annotations for rate limiting, rewrites, auth
  • ✅ IngressClass for controller targeting

🧾 Advanced Ingress with TLS and Multiple Routes

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: secure-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  tls:
  - hosts:
      - app.example.com
    secretName: tls-cert-secret
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 80
      - path: /web
        pathType: Prefix
        backend:
          service:
            name: frontend-service
            port:
              number: 80

📘 Pro Tip: Always use TLS (HTTPS) in production, and use a tool like cert-manager to auto-renew certificates via Let’s Encrypt.


💾 2. Persistent Volumes (PV & PVC) — Store App Data Safely

✅ Why Persistence Matters

In Kubernetes, Pods are ephemeral — they vanish when recreated. For apps like databases, caches, file stores — you need persistent volumes.


🧾 Production-Grade PVC Template

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: gp2  # Replace with your cloud provider class

🧠 Attach this to a Pod or Deployment using volumeMounts.


🧾 Sample Deployment Using a PVC

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis:7
        volumeMounts:
        - mountPath: /data
          name: redis-storage
      volumes:
      - name: redis-storage
        persistentVolumeClaim:
          claimName: data-pvc

🔐 Storage Tips for Production

NeedRecommendation
SSD-backed storageUse storageClassName: gp2, premium-rwo, etc.
Shared read/writeUse ReadWriteMany (e.g., NFS, EFS, Azure Files)
Encryption at restUse cloud-native encrypted disks
BackupAutomate volume snapshotting (Velero, native cloud tools)

⏰ 3. CronJobs — Automate Everything

✅ What is a CronJob?

CronJobs in K8s allow you to run scheduled tasks (like a Linux cron). Perfect for:

  • Database backups
  • Sending emails
  • Periodic health checks

🧾 Basic CronJob Example

apiVersion: batch/v1
kind: CronJob
metadata:
  name: daily-job
spec:
  schedule: "0 2 * * *"  # Daily at 2 AM
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - echo "Hello from Kubernetes"
          restartPolicy: OnFailure

🧾 Advanced CronJob With Resource Limits & Logs

apiVersion: batch/v1
kind: CronJob
metadata:
  name: db-backup
spec:
  schedule: "0 */6 * * *"  # Every 6 hours
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: postgres:15
            resources:
              requests:
                memory: "128Mi"
                cpu: "100m"
              limits:
                memory: "256Mi"
                cpu: "200m"
            env:
              - name: PGUSER
                valueFrom:
                  secretKeyRef:
                    name: pg-secrets
                    key: username
            command: ["pg_dumpall"]
          restartPolicy: OnFailure

✅ CronJob Best Practices

PracticeWhy
Use concurrencyPolicy: ForbidAvoid overlapping jobs
Limit history retentionPrevent clutter & resource waste
Use restartPolicy: OnFailureAvoid retry loops
Attach CPU/memory limitsPrevent runaway pods

🧠 Final Pro Tips

YAML Best PracticeDescription
Use resource limitsPrevent noisy neighbor problems
Use liveness/readiness probesEnsure health before traffic
Split files per resourceEasier debugging and rollbacks
Use Helm or KustomizeParameterize for multiple environments
Validate YAMLUse kubectl apply --dry-run=client -f file.yaml before applying

🏁 Final Thoughts

These YAML templates aren’t just “hello world” — they’re designed for production:

✅ HTTPS Ingress with multiple services
✅ Persistent Volumes with storage classes
✅ CronJobs with retries, logging, concurrency controls

Treat your YAML like code. Reusable, version-controlled, and audited.

Whether you’re deploying a blog, managing backups, or scaling microservices — mastering these templates gives you superpowers in Kubernetes.


Related Posts

Kubernetes RBAC cookbook: common roles (dev, SRE, read-only) safely

Kubernetes RBAC is one of those things that feels annoying until the day it saves your cluster from “oops, I deleted prod.” The tricky part isn’t what…

Read More

General Build Pipeline (CI) in Azure DevOps

Let’s walk through a general-purpose Azure DevOps build pipeline template that can be applied to most common application types (web apps, APIs, microservices, etc.) using CI/CD best…

Read More

Kubernetes Certifications in 2025: Which One Should You Choose?

Kubernetes Certifications in 2025: Which One Should You Choose? Kubernetes has become the cornerstone of modern cloud-native application deployment and orchestration. Whether you’re a beginner just diving…

Read More

Top 5 Kubernetes Tools That Will Replace Your Bash Scripts in 2025

🚀 Top 5 Kubernetes Tools That Will Replace Your Bash Scripts in 2025 For years, DevOps engineers and platform teams have relied on Bash scripts to automate…

Read More

Kubernetes Horror Stories (and What We Learned From Them)

☠️ Kubernetes Horror Stories (and What We Learned From Them) Because what doesn’t kill your cluster makes it stronger. Kubernetes is powerful — but with great power…

Read More

Why Your Kubernetes Costs Are Out of Control – and How to Fix It (2025 Guide)

💸 Why Your Kubernetes Costs Are Out of Control – and How to Fix It (2025 Guide) Kubernetes is powerful — but it isn’t cheap. While it…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x