Biblioteca / YAML / Kubernetes

YAML Deployment Templates - Kubernetes v2.1

22 manifiestos Kubernetes orientados a despliegues empresariales: Deployments Ingress TLS HPA RBAC Sealed Secrets CronJobs.

KubernetesIngressHPAcert-managerRBACSealed SecretsKustomize
YAML + README · 26 paginas + 22 manifiestosNivel: IntermedioActualizado mayo 2026Descargar PDF

Capitulo 1

Guia de uso y estructura

Este paquete contiene 22 manifiestos Kubernetes orientados a entornos empresariales. Cada archivo es independiente disenado para copiarse adaptarse y aplicarse directamente.

Estructura del repositorio

bash - arbol de directorios
k8s-templates/
├── workloads/
│   ├── deployment.yaml
│   ├── statefulset.yaml
│   └── pod-disruption-budget.yaml
├── networking/
│   ├── service-clusterip.yaml
│   ├── ingress-tls.yaml
│   └── network-policy.yaml
├── config/
│   ├── configmap.yaml
│   └── secret-sealed.yaml
├── scaling/
│   ├── hpa.yaml
│   └── resource-quota.yaml
├── security/
│   ├── serviceaccount.yaml
│   └── role-rolebinding.yaml
├── jobs/
│   ├── cronjob.yaml
│   └── job-migration.yaml
├── storage/
│   └── persistent-volume-claim.yaml
└── README.md

Prerrequisitos

ComponenteVersionPara que
kubectl1.28+Aplicar manifiestos
cert-manager1.14+Certificados TLS automaticos
Nginx Ingress1.9+Enrutamiento HTTP/S
Sealed Secrets0.26+Cifrar secrets en git
metrics-server0.7+HPA funcional
Flujo recomendado

Clonar repo copiar manifiestos sustituir placeholders APP_NAME NAMESPACE IMAGE_TAG validar con kubectl apply --dry-run=client y luego aplicar.

Capitulo 2

Workloads Deployment y StatefulSet

El Deployment gestiona replicas actualizaciones rolling y rollbacks automaticamente para aplicaciones sin estado.

Deployment con protecciones de seguridad completas

yaml - deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: APP_NAME
  namespace: NAMESPACE
  labels:
    app.kubernetes.io/name: APP_NAME
spec:
  replicas: 3
  selector:
    matchLabels:
      app.kubernetes.io/name: APP_NAME
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
  template:
    metadata:
      labels:
        app.kubernetes.io/name: APP_NAME
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
    spec:
      serviceAccountName: APP_NAME-sa
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 2000
      containers:
        - name: app
          image: REGISTRY/APP_NAME:IMAGE_TAG
          imagePullPolicy: Always
          ports:
            - { name: http, containerPort: 8080 }
          resources:
            requests: { cpu: "100m", memory: "128Mi" }
            limits:   { cpu: "500m", memory: "512Mi" }
          livenessProbe:
            httpGet: { path: /health, port: 8080 }
            initialDelaySeconds: 30
            periodSeconds: 10
          readinessProbe:
            httpGet: { path: /ready, port: 8080 }
            initialDelaySeconds: 10
            periodSeconds: 5
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }

Capitulo 3

Networking Services e Ingress

El Service expone tu aplicacion dentro del cluster. El Ingress la expone al exterior con TLS automatico.

Ingress TLS con headers de seguridad

yaml - ingress-tls.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: APP_NAME
  namespace: NAMESPACE
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/limit-rps: "50"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      add_header X-Frame-Options "SAMEORIGIN" always;
      add_header X-Content-Type-Options "nosniff" always;
      add_header Strict-Transport-Security "max-age=31536000" always;
spec:
  ingressClassName: nginx
  tls:
    - hosts: [app.tudominio.com]
      secretName: APP_NAME-tls
  rules:
    - host: app.tudominio.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: APP_NAME
                port: { number: 80 }

Capitulo 4

Configuracion y gestion de secretos

Los Secrets nativos de Kubernetes solo estan codificados en base64 no cifrados. Usa Sealed Secrets para produccion.

Sealed Secrets - secretos cifrados en git

bash - crear sealed secret
# 1. Crear el secret NUNCA hacer commit de este archivo
kubectl create secret generic APP_NAME-secrets \
  --from-literal=db-password='supersecreto' \
  --dry-run=client -o yaml > secret.yaml

# 2. Cifrar con kubeseal
kubeseal --format=yaml \
  --cert=https://sealed-secrets.CLUSTER/v1/cert.pem \
  < secret.yaml > sealed-secret.yaml

# 3. El sealed-secret.yaml SI puede ir al repositorio git
git add sealed-secret.yaml
git commit -m "feat: add APP_NAME sealed secrets"

# 4. El controlador descifra y crea el Secret automaticamente
kubectl apply -f sealed-secret.yaml

Capitulo 5

Escalado automatico y gestion de recursos

El HPA garantiza que la aplicacion tiene los recursos que necesita sin pagar de mas cuando la carga es baja.

HorizontalPodAutoscaler por CPU y memoria

yaml - hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: APP_NAME-hpa
  namespace: NAMESPACE
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: APP_NAME
  minReplicas: 2
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: { type: Utilization, averageUtilization: 70 }
    - type: Resource
      resource:
        name: memory
        target: { type: Utilization, averageUtilization: 80 }
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - { type: Percent, value: 25, periodSeconds: 60 }
    scaleUp:
      stabilizationWindowSeconds: 30
      policies:
        - { type: Pods, value: 4, periodSeconds: 30 }

Capitulo 6

Seguridad y control de acceso RBAC

Cada aplicacion debe ejecutarse con el minimo de permisos necesarios.

ServiceAccount y RBAC minimo

yaml - rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: APP_NAME-sa
  namespace: NAMESPACE
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: APP_NAME-role
  namespace: NAMESPACE
rules:
  - apiGroups: [""]
    resources: ["configmaps"]
    verbs: ["get", "list"]
    resourceNames: ["APP_NAME-config"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: APP_NAME-rolebinding
  namespace: NAMESPACE
subjects:
  - kind: ServiceAccount
    name: APP_NAME-sa
    namespace: NAMESPACE
roleRef:
  kind: Role
  apiGroup: rbac.authorization.k8s.io
  name: APP_NAME-role

Capitulo 7

Tareas programadas y trabajos por lote

CronJobs y Jobs son esenciales para migraciones de base de datos y tareas de mantenimiento.

CronJob para tareas periodicas

yaml - cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: APP_NAME-cleanup
  namespace: NAMESPACE
spec:
  schedule: "0 2 * * *"
  timeZone: "America/Costa_Rica"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      backoffLimit: 3
      activeDeadlineSeconds: 3600
      template:
        spec:
          serviceAccountName: APP_NAME-sa
          restartPolicy: OnFailure
          containers:
            - name: cleanup
              image: REGISTRY/APP_NAME:IMAGE_TAG
              command: ["node", "scripts/cleanup.js"]
              resources:
                requests: { cpu: "50m", memory: "64Mi" }
                limits:   { cpu: "200m", memory: "256Mi" }

Job de migracion de base de datos

yaml - job-migration.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: APP_NAME-migration-v1-2-0
  namespace: NAMESPACE
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      initContainers:
        - name: wait-for-db
          image: busybox:1.36
          command: ['sh','-c','until nc -z DB_HOST 5432; do sleep 2; done']
      containers:
        - name: migrate
          image: REGISTRY/APP_NAME:IMAGE_TAG
          command: ["npm", "run", "migrate:prod"]
          resources:
            limits: { cpu: "500m", memory: "512Mi" }

Capitulo 8

Persistencia y observabilidad

El almacenamiento persistente y la observabilidad son las dos piezas finales de un despliegue completo.

PersistentVolumeClaim

yaml - pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: APP_NAME-data
  namespace: NAMESPACE
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: gp3
  resources:
    requests:
      storage: 50Gi

Kustomize overlays por entorno

bash - estructura kustomize
k8s/
├── base/
│   ├── deployment.yaml
│   ├── service.yaml
│   └── kustomization.yaml
└── overlays/
    ├── dev/     # 1 replica imagen :dev
    ├── staging/ # 2 replicas imagen :staging
    └── prod/    # 3+ replicas HPA activo mas recursos

# Aplicar overlay de produccion:
kubectl apply -k k8s/overlays/prod/
Siguiente paso

Con estos 22 manifiestos tienes una base solida para cualquier aplicacion en Kubernetes. El siguiente nivel es GitOps con ArgoCD o Flux CD para sincronizacion automatica entre repositorio y cluster.