Biblioteca / YAML / Kubernetes
YAML Deployment Templates - Kubernetes v2.1
22 manifiestos Kubernetes orientados a despliegues empresariales: Deployments Ingress TLS HPA RBAC Sealed Secrets CronJobs.
Tabla de contenido
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
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
| Componente | Version | Para que |
|---|---|---|
| kubectl | 1.28+ | Aplicar manifiestos |
| cert-manager | 1.14+ | Certificados TLS automaticos |
| Nginx Ingress | 1.9+ | Enrutamiento HTTP/S |
| Sealed Secrets | 0.26+ | Cifrar secrets en git |
| metrics-server | 0.7+ | HPA funcional |
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
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
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
# 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
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
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-roleCapitulo 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
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
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
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: APP_NAME-data
namespace: NAMESPACE
spec:
accessModes: [ReadWriteOnce]
storageClassName: gp3
resources:
requests:
storage: 50GiKustomize overlays por entorno
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/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.