---
title: "kubectl — Référence pratique"
domain: devops
subdomain: kubernetes
type: snippet
tags: [kubernetes, kubectl, k8s, pods, deployments, devops]
difficulty: intermediate
status: stable
updated: "2025-05-10"
---
## Contextes et namespaces

```bash
# Contextes
kubectl config get-contexts
kubectl config current-context
kubectl config use-context {{CONTEXT}}

# Namespace par défaut
kubectl config set-context --current --namespace={{NAMESPACE}}

# Alias utiles
alias k=kubectl
alias kn='kubectl config set-context --current --namespace'
```

## Pods

```bash
# Lister
kubectl get pods
kubectl get pods -n {{NAMESPACE}}
kubectl get pods -A   # tous les namespaces
kubectl get pods -o wide   # avec IP et node

# Détail
kubectl describe pod {{SERVICE}}
kubectl describe pod {{SERVICE}} -n {{NAMESPACE}}

# Logs
kubectl logs {{SERVICE}}
kubectl logs {{SERVICE}} -f                    # suivre
kubectl logs {{SERVICE}} --previous            # crash précédent
kubectl logs {{SERVICE}} -c {{CONTAINER}}      # multi-conteneur
kubectl logs -l app={{SERVICE}} --all-containers  # par label

# Exec
kubectl exec -it {{SERVICE}} -- bash
kubectl exec -it {{SERVICE}} -c {{CONTAINER}} -- sh

# Copier des fichiers
kubectl cp {{SERVICE}}:/path/to/file ./local-file
kubectl cp ./local-file {{SERVICE}}:/path/to/file

# Supprimer
kubectl delete pod {{SERVICE}}
kubectl delete pod {{SERVICE}} --force --grace-period=0
```

## Deployments

```bash
# Lister
kubectl get deployments
kubectl get deploy -n {{NAMESPACE}}

# Détail
kubectl describe deployment {{SERVICE}}

# Scaler
kubectl scale deployment {{SERVICE}} --replicas=3

# Mettre à jour l'image
kubectl set image deployment/{{SERVICE}} {{CONTAINER}}=image:tag

# Rollout
kubectl rollout status deployment/{{SERVICE}}
kubectl rollout history deployment/{{SERVICE}}
kubectl rollout undo deployment/{{SERVICE}}            # rollback
kubectl rollout undo deployment/{{SERVICE}} --to-revision=2

# Redémarrer les pods (sans downtime)
kubectl rollout restart deployment/{{SERVICE}}
```

## Services

```bash
kubectl get services
kubectl get svc -n {{NAMESPACE}}
kubectl describe service {{SERVICE}}

# Port-forward (debug local)
kubectl port-forward service/{{SERVICE}} 8080:80
kubectl port-forward pod/{{SERVICE}} 8080:3000
```

## Configuration

```bash
# ConfigMaps
kubectl get configmap
kubectl describe configmap {{SERVICE}}
kubectl create configmap {{SERVICE}} --from-file=config.yaml
kubectl create configmap {{SERVICE}} --from-literal=key=value

# Secrets
kubectl get secrets
kubectl describe secret {{SERVICE}}
kubectl create secret generic {{SERVICE}} \
  --from-literal=username=admin \
  --from-literal=password=s3cr3t

# Décoder un secret
kubectl get secret {{SERVICE}} -o jsonpath='{.data.password}' | base64 -d
```

## Manifests YAML

### Deployment type

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{SERVICE}}
  namespace: {{NAMESPACE}}
  labels:
    app: {{SERVICE}}
spec:
  replicas: 3
  selector:
    matchLabels:
      app: {{SERVICE}}
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: {{SERVICE}}
    spec:
      containers:
      - name: {{SERVICE}}
        image: myapp:latest
        ports:
        - containerPort: 3000
        env:
        - name: DB_URL
          valueFrom:
            secretKeyRef:
              name: app-secrets
              key: db-url
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 3000
          initialDelaySeconds: 5
          periodSeconds: 5
```

## Appliquer et gérer les ressources

```bash
# Appliquer un manifest
kubectl apply -f deployment.yaml
kubectl apply -f ./k8s/           # tout un répertoire
kubectl apply -k ./kustomize/     # kustomize

# Voir avant d'appliquer (dry-run)
kubectl apply -f deployment.yaml --dry-run=client
kubectl diff -f deployment.yaml

# Supprimer
kubectl delete -f deployment.yaml
kubectl delete deployment {{SERVICE}}

# Éditer en direct
kubectl edit deployment {{SERVICE}}
```

## Nodes et cluster

```bash
# Nodes
kubectl get nodes
kubectl get nodes -o wide
kubectl describe node {{SERVICE}}
kubectl top nodes                  # CPU/RAM (metrics-server requis)

# Cordon / drain (maintenance)
kubectl cordon {{SERVICE}}         # plus de scheduling
kubectl drain {{SERVICE}} --ignore-daemonsets --delete-emptydir-data
kubectl uncordon {{SERVICE}}       # réactiver

# Pods par node
kubectl get pods -A -o wide | grep {{SERVICE}}

# Events du cluster
kubectl get events -A --sort-by='.lastTimestamp' | tail -20
kubectl get events -n {{NAMESPACE}} --field-selector reason=BackOff
```

## Troubleshooting

```bash
# Pod en CrashLoopBackOff
kubectl logs {{SERVICE}} --previous
kubectl describe pod {{SERVICE}}   # Events en bas

# Pod en Pending
kubectl describe pod {{SERVICE}}   # chercher "Insufficient cpu/memory"
kubectl get events | grep {{SERVICE}}

# Image pull error
kubectl describe pod {{SERVICE}}   # "ErrImagePull" ou "ImagePullBackOff"
# Vérifier le secret de registry :
kubectl get secret regcred

# Debug avec un pod éphémère
kubectl debug -it {{SERVICE}} --image=busybox --target={{CONTAINER}}
kubectl run debug --image=nicolaka/netshoot -it --rm
```

<Tip>
Toujours définir `resources.requests` et `resources.limits` sur les containers de production. Sans requests, le scheduler ne peut pas placer correctement les pods. Sans limits, un pod peut monopoliser les ressources du node et impacter les autres.
</Tip>
