kubectl: Comandos Esenciales - Guía de Referencia Completa

kubectl es la herramienta de línea de comandos para interactuar con clusters de Kubernetes. Dominar kubectl es esencial para gestionar recursos de Kubernetes, depurar aplicaciones y realizar operaciones diarias del cluster. Esta guía completa cubre todos los comandos esenciales de kubectl con ejemplos prácticos y mejores prácticas.

Tabla de Contenidos

Introducción

kubectl (Kube Control) se comunica con el servidor API de Kubernetes para ejecutar comandos. Entender la sintaxis de kubectl y las operaciones comunes es fundamental para la administración de Kubernetes.

Sintaxis de kubectl

kubectl [command] [TYPE] [NAME] [flags]

# Examples:
kubectl get pods
kubectl describe pod my-pod
kubectl delete deployment nginx
kubectl logs pod-name --tail=100

Obtener Ayuda

# General help
kubectl help
kubectl --help

# Command-specific help
kubectl get --help
kubectl create --help

# Explain resource
kubectl explain pods
kubectl explain deployment.spec

Configuración y Contexto

Ver Configuración

# Show current context
kubectl config current-context

# View all contexts
kubectl config get-contexts

# View config file
kubectl config view

# View config with secrets
kubectl config view --raw

Gestionar Contextos

# Switch context
kubectl config use-context my-context

# Set default namespace for context
kubectl config set-context --current --namespace=my-namespace

# Create new context
kubectl config set-context dev \
  --cluster=my-cluster \
  --namespace=development \
  --user=dev-user

# Rename context
kubectl config rename-context old-name new-name

# Delete context
kubectl config delete-context my-context

Múltiples Clusters

# Specify kubeconfig file
kubectl --kubeconfig=/path/to/config get pods

# Set KUBECONFIG environment variable
export KUBECONFIG=~/.kube/config:~/.kube/config-cluster2

# Merge kubeconfig files
KUBECONFIG=~/.kube/config:~/.kube/config2 kubectl config view --flatten > ~/.kube/merged-config

Gestión de Recursos

Obtener Recursos

# List all pods
kubectl get pods

# All namespaces
kubectl get pods -A
kubectl get pods --all-namespaces

# Specific namespace
kubectl get pods -n kube-system

# With labels
kubectl get pods --show-labels

# Filter by label
kubectl get pods -l app=nginx
kubectl get pods -l 'environment in (production,staging)'

# Wide output (more details)
kubectl get pods -o wide

# Custom output format
kubectl get pods -o json
kubectl get pods -o yaml
kubectl get pods -o name

Describir Recursos

# Detailed information
kubectl describe pod my-pod
kubectl describe service my-service
kubectl describe deployment my-deployment

# Describe all pods
kubectl describe pods

# Describe in specific namespace
kubectl describe pod my-pod -n my-namespace

Crear Recursos

# From file
kubectl create -f pod.yaml
kubectl apply -f deployment.yaml

# From directory
kubectl apply -f ./manifests/

# From URL
kubectl apply -f https://example.com/deployment.yaml

# Create deployment imperatively
kubectl create deployment nginx --image=nginx:alpine

# Create service
kubectl create service clusterip my-service --tcp=80:8080

# Dry-run (test without creating)
kubectl create deployment test --image=nginx --dry-run=client -o yaml

Actualizar Recursos

# Apply changes from file
kubectl apply -f deployment.yaml

# Edit resource in editor
kubectl edit deployment nginx

# Patch resource
kubectl patch deployment nginx -p '{"spec":{"replicas":5}}'

# Set image
kubectl set image deployment/nginx nginx=nginx:1.26

# Set resources
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi

Eliminar Recursos

# Delete specific resource
kubectl delete pod my-pod
kubectl delete deployment my-deployment

# Delete from file
kubectl delete -f deployment.yaml

# Delete all pods with label
kubectl delete pods -l app=nginx

# Delete all resources in namespace
kubectl delete all --all -n my-namespace

# Force delete
kubectl delete pod my-pod --force --grace-period=0

# Delete namespace (cascade deletes all resources)
kubectl delete namespace my-namespace

Pods y Contenedores

Ver Pods

# List pods
kubectl get pods

# Watch pods (live updates)
kubectl get pods -w
kubectl get pods --watch

# Sort by creation time
kubectl get pods --sort-by=.metadata.creationTimestamp

# Filter by status
kubectl get pods --field-selector=status.phase=Running
kubectl get pods --field-selector=status.phase=Failed

# Show resource usage
kubectl top pods
kubectl top pods --containers

Ejecutar Pods

# Run single pod
kubectl run nginx --image=nginx:alpine

# Run with custom command
kubectl run busybox --image=busybox --command -- sleep 3600

# Run interactive pod
kubectl run -it debug --image=busybox --rm -- sh

# Run with environment variables
kubectl run nginx --image=nginx --env="ENV=production"

# Run with labels
kubectl run nginx --image=nginx --labels="app=web,env=prod"

# Run with resource limits
kubectl run nginx --image=nginx --requests='cpu=100m,memory=256Mi' --limits='cpu=200m,memory=512Mi'

Acceder a Pods

# View logs
kubectl logs my-pod

# Follow logs
kubectl logs -f my-pod

# Last 100 lines
kubectl logs my-pod --tail=100

# Logs from previous container
kubectl logs my-pod --previous

# Logs from specific container
kubectl logs my-pod -c container-name

# Logs with timestamps
kubectl logs my-pod --timestamps

# Execute command in pod
kubectl exec my-pod -- ls /app

# Interactive shell
kubectl exec -it my-pod -- bash
kubectl exec -it my-pod -- sh

# Execute in specific container
kubectl exec -it my-pod -c container-name -- sh

Reenvío de Puertos

# Forward local port to pod
kubectl port-forward pod/my-pod 8080:80

# Forward to service
kubectl port-forward service/my-service 8080:80

# Forward to deployment
kubectl port-forward deployment/nginx 8080:80

# Listen on all interfaces
kubectl port-forward --address 0.0.0.0 pod/my-pod 8080:80

Copiar Archivos

# Copy from pod to local
kubectl cp my-pod:/path/to/file ./local-file

# Copy from local to pod
kubectl cp ./local-file my-pod:/path/to/file

# Copy from specific container
kubectl cp my-pod:/path/to/file ./local-file -c container-name

# Copy directory
kubectl cp my-pod:/app/logs ./logs/

Despliegues y Escalado

Gestionar Despliegues

# List deployments
kubectl get deployments

# Create deployment
kubectl create deployment nginx --image=nginx:alpine --replicas=3

# Scale deployment
kubectl scale deployment nginx --replicas=5

# Autoscale
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80

# View autoscaler
kubectl get hpa

Actualizaciones Graduales

# Update image
kubectl set image deployment/nginx nginx=nginx:1.26-alpine

# Update with record
kubectl set image deployment/nginx nginx=nginx:1.26 --record

# View rollout status
kubectl rollout status deployment/nginx

# View rollout history
kubectl rollout history deployment/nginx

# View specific revision
kubectl rollout history deployment/nginx --revision=2

# Pause rollout
kubectl rollout pause deployment/nginx

# Resume rollout
kubectl rollout resume deployment/nginx

# Undo rollout
kubectl rollout undo deployment/nginx

# Rollback to specific revision
kubectl rollout undo deployment/nginx --to-revision=2

# Restart deployment
kubectl rollout restart deployment/nginx

Servicios y Redes

Gestionar Servicios

# List services
kubectl get services
kubectl get svc

# Create ClusterIP service
kubectl create service clusterip my-service --tcp=80:8080

# Create NodePort service
kubectl create service nodeport my-service --tcp=80:8080 --node-port=30080

# Expose deployment as service
kubectl expose deployment nginx --port=80 --target-port=8080

# Expose with type
kubectl expose deployment nginx --type=NodePort --port=80

Endpoints de Servicio

# View service endpoints
kubectl get endpoints my-service

# Describe endpoints
kubectl describe endpoints my-service

Ingress

# List ingress resources
kubectl get ingress

# Describe ingress
kubectl describe ingress my-ingress

# Create ingress
kubectl create ingress my-ingress \
  --rule="example.com/*=my-service:80"

ConfigMaps y Secrets

ConfigMaps

# Create from literal
kubectl create configmap app-config \
  --from-literal=database_url=postgres://db:5432 \
  --from-literal=log_level=info

# Create from file
kubectl create configmap app-config --from-file=config.properties

# Create from directory
kubectl create configmap app-config --from-file=./config/

# View ConfigMap
kubectl get configmap app-config
kubectl describe configmap app-config
kubectl get configmap app-config -o yaml

# Edit ConfigMap
kubectl edit configmap app-config

# Delete ConfigMap
kubectl delete configmap app-config

Secrets

# Create secret from literal
kubectl create secret generic db-secret \
  --from-literal=username=admin \
  --from-literal=password=secret123

# Create secret from file
kubectl create secret generic tls-secret \
  --from-file=tls.crt=./cert.pem \
  --from-file=tls.key=./key.pem

# Create TLS secret
kubectl create secret tls tls-secret \
  --cert=./cert.pem \
  --key=./key.pem

# Create Docker registry secret
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=user \
  --docker-password=pass \
  [email protected]

# View secrets
kubectl get secrets
kubectl describe secret db-secret

# Decode secret
kubectl get secret db-secret -o jsonpath='{.data.password}' | base64 --decode

# Delete secret
kubectl delete secret db-secret

Comandos de Solución de Problemas

Información del Cluster

# Cluster info
kubectl cluster-info

# View cluster components
kubectl get componentstatuses
kubectl get cs

# View nodes
kubectl get nodes
kubectl describe node node-name
kubectl top nodes

Eventos

# View all events
kubectl get events

# Sort by timestamp
kubectl get events --sort-by='.lastTimestamp'

# Events in specific namespace
kubectl get events -n kube-system

# Watch events
kubectl get events -w

Uso de Recursos

# Node metrics
kubectl top nodes

# Pod metrics
kubectl top pods

# Pod metrics in namespace
kubectl top pods -n kube-system

# Container metrics
kubectl top pods --containers

# Metrics for specific pod
kubectl top pod my-pod

Depuración

# Debug pod
kubectl debug my-pod -it --image=busybox

# Debug node
kubectl debug node/node-name -it --image=busybox

# Run debug container in existing pod
kubectl debug my-pod --image=busybox --target=container-name

# Attach to pod
kubectl attach my-pod -i

# Show pod processes
kubectl top pods --containers

Operaciones Avanzadas

Etiquetas y Anotaciones

# Add label
kubectl label pods my-pod environment=production

# Update label
kubectl label pods my-pod environment=staging --overwrite

# Remove label
kubectl label pods my-pod environment-

# Add annotation
kubectl annotate pods my-pod description="Web server pod"

# Remove annotation
kubectl annotate pods my-pod description-

Filtrado de Recursos

# Field selectors
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=node-1

# Label selectors
kubectl get pods -l app=nginx
kubectl get pods -l 'app in (nginx,apache)'
kubectl get pods -l app=nginx,env=prod

# Multiple conditions
kubectl get pods --field-selector status.phase=Running -l app=nginx

Salida YAML y JSON

# Get YAML
kubectl get pod my-pod -o yaml

# Get JSON
kubectl get pod my-pod -o json

# JSONPath (specific fields)
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{.items[*].status.podIP}'

# Custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP

# Go template
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'

Recursos de API

# List all API resources
kubectl api-resources

# List resources with short names
kubectl api-resources -o wide

# List namespaced resources
kubectl api-resources --namespaced=true

# List cluster-wide resources
kubectl api-resources --namespaced=false

# Get API versions
kubectl api-versions

Gestión de Plugins

# List plugins
kubectl plugin list

# Install krew (plugin manager)
kubectl krew install krew

# Install plugins with krew
kubectl krew install ctx
kubectl krew install ns

# Use plugins
kubectl ctx  # List contexts
kubectl ns   # List namespaces

Consejos de Productividad

Alias y Funciones

# Add to ~/.bashrc or ~/.zshrc

# Basic aliases
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias kl='kubectl logs'
alias ke='kubectl exec -it'

# Advanced aliases
alias kgp='kubectl get pods'
alias kgs='kubectl get services'
alias kgd='kubectl get deployments'
alias kgn='kubectl get nodes'

# Function for namespace switching
kns() {
  kubectl config set-context --current --namespace=$1
}

# Function for quick pod logs
klf() {
  kubectl logs -f $1
}

Autocompletado de Bash

# Install bash-completion
sudo apt-get install bash-completion

# Enable kubectl completion
echo 'source <(kubectl completion bash)' >> ~/.bashrc
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -F __start_kubectl k' >> ~/.bashrc

# For zsh
echo 'source <(kubectl completion zsh)' >> ~/.zshrc

Atajos Útiles

# Short resource names
k get po      # pods
k get svc     # services
k get deploy  # deployments
k get rs      # replicasets
k get cm      # configmaps
k get ns      # namespaces

# Quick pod shell access
k exec -it <pod> -- sh

# Quick service test
k run curl --image=curlimages/curl --rm -it -- curl http://service-name

Conclusión

Dominar kubectl es esencial para una gestión efectiva del cluster de Kubernetes. Estos comandos forman la base de las operaciones diarias, solución de problemas y automatización.

Puntos Clave

  • Gestión de Contexto: Cambiar entre clusters y namespaces eficientemente
  • Operaciones de Recursos: Crear, leer, actualizar, eliminar recursos
  • Depuración: Logs, exec, describe, eventos para solución de problemas
  • Productividad: Usar alias, autocompletado y atajos
  • Avanzado: JSONPath, filtrado y exploración de API

Referencia de Comandos Esenciales

# Configuration
kubectl config current-context
kubectl config use-context <context>
kubectl config set-context --current --namespace=<ns>

# Resources
kubectl get <resource>
kubectl describe <resource> <name>
kubectl create -f <file>
kubectl apply -f <file>
kubectl delete <resource> <name>

# Pods
kubectl get pods
kubectl logs <pod>
kubectl exec -it <pod> -- sh
kubectl port-forward <pod> 8080:80

# Deployments
kubectl scale deployment <name> --replicas=<num>
kubectl set image deployment/<name> container=image:tag
kubectl rollout status deployment/<name>
kubectl rollout undo deployment/<name>

# Troubleshooting
kubectl describe pod <name>
kubectl logs -f <pod>
kubectl get events --sort-by='.lastTimestamp'
kubectl top pods

Próximos Pasos

  1. Práctica: Usar kubectl diariamente para familiaridad
  2. Automatización: Escribir scripts y usar kubectl en CI/CD
  3. Personalizar: Crear alias y funciones personales
  4. Explorar: Probar plugins de kubectl vía krew
  5. Monitorear: Combinar con herramientas de monitoreo
  6. Aprender: Estudiar JSONPath y plantillas Go
  7. Contribuir: Extender kubectl con plugins personalizados

kubectl es tu interfaz principal a Kubernetes. ¡Domínalo para ser competente en la gestión de clusters!