Kubernetes & Infrastructure as Code
Guide de deploiement Kubernetes et Infrastructure as Code (IaC) pour MyTelevision API.
Structure des repertoires
mytelevision-api/
├── iac/ # Terraform Infrastructure
│ ├── modules/ # Modules reutilisables
│ │ ├── network/ # VPC, Subnets, Security Groups
│ │ ├── compute/ # ECS/EKS, Auto Scaling
│ │ ├── database/ # RDS PostgreSQL
│ │ ├── storage/ # S3/R2, CloudFront
│ │ ├── observability/ # CloudWatch, Prometheus
│ │ └── security/ # IAM, Secrets Manager, KMS
│ ├── environments/ # Configurations par environnement
│ │ ├── dev/
│ │ ├── staging/
│ │ └── prod/
│ └── shared/ # Configuration partagee
├── k8s/ # Manifestes Kubernetes
│ ├── base/ # Manifestes de base
│ │ ├── namespace.yaml
│ │ ├── configmap.yaml
│ │ ├── secrets.yaml.example
│ │ ├── deployment.yaml
│ │ ├── service.yaml
│ │ ├── ingress.yaml
│ │ ├── hpa.yaml
│ │ ├── pdb.yaml
│ │ ├── serviceaccount.yaml
│ │ └── networkpolicy.yaml
│ └── overlays/
│ ├── staging/
│ │ ├── kustomization.yaml
│ │ └── patches/
│ └── production/
│ ├── kustomization.yaml
│ └── patches/
└── helm/ # Helm Charts
└── mytv-api/
├── Chart.yaml
├── values.yaml
└── templates/
Deploiement Kubernetes
Staging
kubectl apply -k k8s/overlays/staging/
Production
kubectl apply -k k8s/overlays/production/
Verification
# Pods
kubectl get pods -n mytv
# Logs
kubectl logs -f deployment/mytv-api -n mytv
# Describe
kubectl describe deployment mytv-api -n mytv
Manifests Kubernetes
Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: mytv-api
namespace: mytv
spec:
replicas: 3
selector:
matchLabels:
app: mytv-api
template:
metadata:
labels:
app: mytv-api
spec:
containers:
- name: api
image: registry/mytv-api:latest
ports:
- containerPort: 3000
env:
- name: NODE_ENV
value: production
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: mytv-secrets
key: database-url
resources:
requests:
cpu: 250m
memory: 512Mi
limits:
cpu: 1000m
memory: 1Gi
livenessProbe:
httpGet:
path: /api/v2/health/live
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /api/v2/health/live
port: 3000
initialDelaySeconds: 5
periodSeconds: 5
Service
apiVersion: v1
kind: Service
metadata:
name: mytv-api
namespace: mytv
spec:
type: ClusterIP
selector:
app: mytv-api
ports:
- port: 80
targetPort: 3000
HPA (Horizontal Pod Autoscaler)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: mytv-api-hpa
namespace: mytv
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: mytv-api
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: mytv-api-ingress
namespace: mytv
annotations:
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
tls:
- hosts:
- api.mytelevision.app
secretName: mytv-api-tls
rules:
- host: api.mytelevision.app
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: mytv-api
port:
number: 80
Manifestes de base
| Fichier | Description |
|---|---|
namespace.yaml | Namespace dedie mytv |
configmap.yaml | Configuration non-sensible |
secrets.yaml.example | Template pour les secrets |
deployment.yaml | Deploiement de l'API (2 replicas) |
service.yaml | Service ClusterIP + Headless |
ingress.yaml | Ingress NGINX avec TLS |
hpa.yaml | Auto-scaling horizontal |
pdb.yaml | Pod Disruption Budget |
serviceaccount.yaml | ServiceAccount + RBAC |
networkpolicy.yaml | Politiques reseau |
Securite Kubernetes
Pod Security
runAsNonRoot: truerunAsUser: 1001readOnlyRootFilesystem: trueallowPrivilegeEscalation: false
Network Policies
- Deny all par defaut
- Autorisation explicite vers PostgreSQL/Redis
- Autorisation HTTPS sortant pour APIs externes
RBAC
- ServiceAccount dedie
- Permissions minimales (lecture ConfigMaps/Secrets)
Secrets Kubernetes
# Creer secrets
kubectl create secret generic mytv-secrets \
--from-literal=JWT_SECRET=xxx \
--from-literal=DATABASE_URL=xxx \
-n mytv
# Depuis fichier
kubectl create secret generic mytv-secrets \
--from-env-file=.env.production \
-n mytv
Helm Chart
Installation
# Ajouter les dependances
cd helm/mytv-api
helm dependency update
# Installation (dev)
helm install mytv-api . \
--namespace mytv \
--create-namespace \
-f values.yaml \
--set existingSecret=mytv-api-secrets
# Installation (production)
helm install mytv-api . \
--namespace mytv \
--create-namespace \
-f values.yaml \
-f values-prod.yaml
Valeurs configurables
| Parametre | Description | Defaut |
|---|---|---|
replicaCount | Nombre de replicas | 2 |
image.repository | Image Docker | mytv/api |
image.tag | Tag de l'image | Chart.appVersion |
resources.requests.cpu | CPU demande | 100m |
resources.requests.memory | Memoire demandee | 256Mi |
resources.limits.cpu | CPU limite | 500m |
resources.limits.memory | Memoire limite | 512Mi |
autoscaling.enabled | Activer HPA | true |
autoscaling.minReplicas | Min replicas | 2 |
autoscaling.maxReplicas | Max replicas | 10 |
ingress.enabled | Activer Ingress | true |
ingress.hosts[0].host | Hostname | api.mytelevision.app |
Mise a jour
# Mettre a jour l'application
helm upgrade mytv-api . \
--namespace mytv \
--reuse-values \
--set image.tag=v2.1.0
Rolling Update
# Mettre a jour l'image
kubectl set image deployment/mytv-api api=registry/mytv-api:v2.1.0 -n mytv
# Verifier le status
kubectl rollout status deployment/mytv-api -n mytv
# Rollback si probleme
kubectl rollout undo deployment/mytv-api -n mytv
# Historique
kubectl rollout history deployment/mytv-api -n mytv
Infrastructure Terraform
Architecture Cloud (AWS)
┌─────────────────────────────────────────────────────────────────────────────────┐
│ AWS Cloud │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ VPC (10.0.0.0/16) │ │
│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Public Subnets: ALB, NAT Gateway │ │ │
│ │ └──────────────────────────────────────────────────────────────────┘ │ │
│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Private Subnets: ECS/EKS API Pods (multi-AZ) │ │ │
│ │ └──────────────────────────────────────────────────────────────────┘ │ │
│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Data Subnets: RDS PostgreSQL, ElastiCache Redis │ │ │
│ │ └──────────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
Modules Terraform
| Module | Description |
|---|---|
network | VPC, Subnets, Security Groups, NAT Gateway |
compute | ECS/EKS, Auto Scaling |
database | RDS PostgreSQL |
storage | S3/R2, CloudFront |
observability | CloudWatch, Prometheus |
security | IAM, Secrets Manager, KMS |
Security Groups
| Security Group | Ingress | Source |
|---|---|---|
| ALB | 80, 443 | 0.0.0.0/0 |
| API | 3000 | ALB SG |
| Database | 5432 | API SG |
| Redis | 6379 | API SG |
Environnements Terraform
| Environnement | NAT Gateway | Instances | Multi-AZ RDS | Deletion Protection |
|---|---|---|---|---|
| dev | Single | t3.micro | Non | Non |
| staging | Single | t3.small | Oui | Oui |
| prod | Multi-AZ | t3.medium+ | Oui | Oui |
Commandes Terraform
cd iac/environments/dev
terraform init
terraform plan
terraform apply
CI/CD avec Helm
# .github/workflows/deploy.yml
- name: Deploy to Kubernetes
run: |
helm upgrade --install mytv-api ./helm/mytv-api \
--namespace mytv \
--set image.tag=${{ github.sha }}
ArgoCD (GitOps)
# argocd/application.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: mytv-api
spec:
source:
repoURL: https://github.com/XKS-MYTV4JS/mytelevision-restfullapijsv4
path: helm/mytv-api
helm:
valueFiles:
- values.yaml
- values-prod.yaml
Troubleshooting
# Logs d'un pod
kubectl logs <pod-name> -n mytv
# Logs precedents (si crash)
kubectl logs <pod-name> -n mytv --previous
# Shell dans un pod
kubectl exec -it <pod-name> -n mytv -- /bin/sh
# Describe pod
kubectl describe pod <pod-name> -n mytv
# Events du namespace
kubectl get events -n mytv --sort-by='.lastTimestamp'
Commandes utiles
# Kubernetes
kubectl get all -n mytv # Voir toutes les ressources
kubectl logs -f -l app=mytv-api # Logs en temps reel
kubectl describe pod <pod-name> # Details d'un pod
kubectl top pods -n mytv # Utilisation ressources
# Helm
helm list -n mytv # Lister les releases
helm history mytv-api -n mytv # Historique
helm rollback mytv-api 1 -n mytv # Rollback
helm template mytv-api . # Previsualiser les manifestes
helm lint . # Valider le chart
# Terraform
terraform init # Initialiser
terraform plan # Previsualiser
terraform apply # Appliquer
terraform destroy # Detruire
terraform state list # Lister les ressources
Bonnes pratiques
Kubernetes / Helm
- Secrets : Utiliser External Secrets Operator ou Vault
- Resources : Toujours definir requests/limits
- Health checks : Configurer liveness/readiness probes
- Security : Network Policies + Pod Security
Terraform
- State management : Utiliser un backend distant (S3/GCS)
- Modules : Reutiliser les modules entre environnements
- Variables : Separer configuration sensible (tfvars)
- Locking : DynamoDB pour le verrouillage d'etat