Skip to content

Linkerd

Linkerd es un service mesh ligero y de alto rendimiento diseñado para simplificar la gestión de la comunicación entre servicios en arquitecturas de microservicios. Proporciona características esenciales como descubrimiento de servicios, balanceo de carga, seguridad y monitoreo, todo ello con una configuración mínima.

Conceptos clave

  • Service Mesh: Capa de infraestructura para comunicación entre servicios
  • Data Plane: Proxies ligeros (Linkerd2-proxy) junto a cada servicio
  • Control Plane: Componentes que gestionan y configuran el data plane
  • mTLS: Encriptación automática entre servicios
  • Traffic Split: División de tráfico para canary deployments
  • Service Profile: Configuración de rutas y timeouts por servicio

Ventajas de Linkerd

  • Ligero: Proxy ultra-rápido escrito en Rust
  • Simplicidad: Configuración mínima y fácil de usar
  • Seguridad: mTLS automático sin configuración
  • Observabilidad: Métricas y trazas integradas
  • Confiabilidad: Reintentos y timeouts automáticos
  • CNCF: Proyecto graduado de Cloud Native Computing Foundation

Esta es una guía esencial para introducirse en service-mesh (maya de servicios) con Linkerd

Instalación y configuración de Linkerd

Requisitos previos

  • Kubernetes cluster (minikube, kind, o cloud provider)
  • kubectl configurado

Instalación de Linkerd CLI

bash
# Linux/macOS
curl -fsL https://run.linkerd.io/install | sh

# Agregar al PATH
export PATH=$PATH:$HOME/.linkerd2/bin

# macOS con Homebrew
brew install linkerd

# Verificar instalación
linkerd version

Validar cluster de Kubernetes

bash
# Verificar que el cluster esté listo
linkerd check --pre

Instalar Linkerd en el cluster

bash
# Instalar control plane
linkerd install --crds | kubectl apply -f -
linkerd install | kubectl apply -f -

# Verificar instalación
linkerd check

# Instalar dashboard (opcional)
linkerd viz install | kubectl apply -f -

# Abrir dashboard
linkerd viz dashboard

Operaciones básicas

Inyectar Linkerd en aplicaciones

bash
# Inyectar en un deployment existente
kubectl get deploy -n myapp -o yaml | \
  linkerd inject - | \
  kubectl apply -f -

# Inyectar en un namespace completo
kubectl annotate namespace myapp linkerd.io/inject=enabled

# Verificar pods con Linkerd
kubectl get pods -n myapp -o jsonpath='{.items[*].spec.containers[*].name}'

Ver métricas y estadísticas

bash
# Ver estadísticas de un deployment
linkerd viz stat deploy -n myapp

# Ver rutas de un servicio
linkerd viz routes deploy/web -n myapp

# Ver top de servicios por tráfico
linkerd viz top deploy -n myapp

# Ver conexiones activas
linkerd viz tap deploy/web -n myapp

Traffic Split (Canary Deployments)

yaml
# traffic-split.yaml
apiVersion: split.smi-spec.io/v1alpha1
kind: TrafficSplit
metadata:
  name: web-split
  namespace: myapp
spec:
  service: web
  backends:
  - service: web-v1
    weight: 90
  - service: web-v2
    weight: 10

Aplicar:

bash
kubectl apply -f traffic-split.yaml

Ejemplo de aplicación con Linkerd

Desplegar aplicación de ejemplo

bash
# Instalar aplicación demo de Linkerd
curl -fsL https://run.linkerd.io/emojivoto.yml | kubectl apply -f -

# Inyectar Linkerd
kubectl get deploy -n emojivoto -o yaml | \
  linkerd inject - | \
  kubectl apply -f -

# Verificar
linkerd viz stat deploy -n emojivoto

# Acceder a la aplicación
kubectl port-forward -n emojivoto svc/web-svc 8080:80

Service Profile para configuración avanzada

yaml
# service-profile.yaml
apiVersion: linkerd.io/v1alpha2
kind: ServiceProfile
metadata:
  name: web.myapp.svc.cluster.local
  namespace: myapp
spec:
  routes:
  - name: GET /api/users
    condition:
      method: GET
      pathRegex: /api/users
    timeout: 5s
    retries:
      limit: 3
      timeout: 1s
  - name: POST /api/users
    condition:
      method: POST
      pathRegex: /api/users
    timeout: 10s

Aplicar:

bash
kubectl apply -f service-profile.yaml

Configuración de mTLS

bash
# Verificar que mTLS esté habilitado
linkerd viz edges deployment -n myapp

# Ver certificados
linkerd identity -n myapp

# Rotar certificados
linkerd upgrade --identity-issuer-certificate-file=ca.crt \
  --identity-issuer-key-file=ca.key | \
  kubectl apply -f -

Monitoreo y observabilidad

Integración con Prometheus

bash
# Linkerd expone métricas en formato Prometheus
kubectl port-forward -n linkerd-viz svc/prometheus 9090:9090

# Consultas útiles en Prometheus:
# - rate(request_total[1m])
# - histogram_quantile(0.99, request_latency_ms_bucket)

Integración con Grafana

bash
# Acceder a Grafana incluido
kubectl port-forward -n linkerd-viz svc/grafana 3000:3000

# Dashboards predefinidos:
# - Linkerd Top Line
# - Linkerd Deployment
# - Linkerd Pod

Ejemplo con Docker Compose (desarrollo local)

Para desarrollo local sin Kubernetes:

yaml
version: '3.8'

services:
  web:
    image: myapp/web:latest
    ports:
      - "8080:8080"
    environment:
      API_URL: http://api:3000

  api:
    image: myapp/api:latest
    ports:
      - "3000:3000"
    environment:
      DB_HOST: postgres

  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_PASSWORD: secret

Nota: Linkerd está diseñado principalmente para Kubernetes. Para Docker Compose, considera usar Consul Connect o Traefik.

Comandos útiles

bash
# Ver versión de Linkerd
linkerd version

# Verificar salud del control plane
linkerd check

# Ver logs del control plane
kubectl logs -n linkerd -l linkerd.io/control-plane-component=controller

# Desinstalar Linkerd
linkerd viz uninstall | kubectl delete -f -
linkerd uninstall | kubectl delete -f -

# Generar Service Profile automáticamente
linkerd viz profile -n myapp web --tap deploy/web --tap-duration 60s

Mejores prácticas

  • Inyección automática: Usar anotaciones en namespaces
  • Service Profiles: Definir para servicios críticos
  • Monitoreo: Configurar alertas en Prometheus
  • Actualizaciones: Mantener Linkerd actualizado
  • Recursos: Ajustar límites de CPU/memoria según carga
  • mTLS: Rotar certificados regularmente

Comparación con otras soluciones

CaracterísticaLinkerdIstioConsul Connect
ComplejidadBajaAltaMedia
RendimientoExcelenteBuenoMuy bueno
RecursosMínimosAltosMedios
mTLSAutomáticoManualAutomático
Curva aprendizajeSuavePronunciadaMedia

Linkerd es ideal para equipos que buscan un service mesh simple, rápido y confiable sin la complejidad de soluciones más pesadas. Es especialmente adecuado para arquitecturas de microservicios en Kubernetes que requieren seguridad y observabilidad con mínima configuración.