Saltar al contenido

Uso de Ingress de Kubernetes en OpenShift: Cómo se Generan las Rutas y Cuándo Usar Cada Una

Introducción
OpenShift, la plataforma de Kubernetes de Red Hat, tiene su propia forma de exponer servicios a clientes externos. En Kubernetes estándar, normalmente usarías un recurso de Ingreso junto con un controlador de ingreso para enrutar el tráfico externo a los servicios. Sin embargo, OpenShift introdujo el concepto de un Ruta y un Enrutador integrado (construido sobre HAProxy) desde el principio, antes de que el Ingreso de Kubernetes siquiera existiera. Hoy en día, OpenShift admite tanto Rutas como objetos de Ingreso estándar, lo que a veces puede llevar a confusión sobre cuándo usar cada uno y cómo se relacionan.

Este artículo explora cómo OpenShift maneja los recursos de Ingreso de Kubernetes, cómo se traducen en Rutas, las limitaciones de este enfoque y orientación sobre cuándo usar Ingreso versus Rutas.

Rutas de OpenShift y el Enrutador: Una Visión Rápida


Las Rutas de OpenShift son recursos específicos de OpenShift diseñados para exponer servicios externamente. Son servidas por el Enrutador de OpenShift, que es un proxy basado en HAProxy que se ejecuta dentro del clúster. Las Rutas admiten características avanzadas como:

  • Backends ponderados para división de tráfico
  • Sesiones persistentes (afinidad de sesión)
  • Múltiples modos de terminación TLS (borde, paso a través, re-encriptar)
  • Subdominios comodín
  • Certificados personalizados y SNI
  • Enrutamiento basado en rutas

Debido a que las Rutas son nativas de OpenShift, el Enrutador entiende estas características de manera nativa y puede configurarse en consecuencia. Esta integración estrecha permite capacidades de enrutamiento poderosas y flexibles adaptadas a los entornos de OpenShift.

Uso de Ingreso de Kubernetes en OpenShift (Comportamiento Predeterminado)


A partir de OpenShift Container Platform (OCP) 3.10, se admiten los recursos de Ingreso de Kubernetes. Cuando creas un Ingreso, OpenShift lo traduce automáticamente en una Ruta equivalente detrás de escena. Esto significa que puedes usar manifiestos estándar de Ingreso de Kubernetes, y OpenShift se encargará de exponer tus servicios externamente creando Rutas en consecuencia.

Ejemplo: Ingreso de Kubernetes y Ruta Resultante

Aquí hay un manifiesto de Ingreso simple:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /testpath
        pathType: Prefix
        backend:
          service:
            name: test-service
            port:
              number: 80

OpenShift creará una Ruta similar a:

apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: example-route
spec:
  host: www.example.com
  path: /testpath
  to:
    kind: Service
    name: test-service
    weight: 100
  port:
    targetPort: 80
  tls:
    termination: edge

Esta traducción automática simplifica la migración y admite casos de uso básicos sin requerir manifiestos específicos de Ruta.

Ajuste del Comportamiento con Anotaciones (Ingreso ➝ Ruta)

Cuando usas Ingreso en OpenShift, solo se respetan las anotaciones conscientes de OpenShift durante la traducción de Ingreso ➝ Ruta. Las anotaciones específicas del controlador para otros controladores de ingreso (por ejemplo, nginx.ingress.kubernetes.io/*) son ignoradas por el Enrutador de OpenShift. Las siguientes anotaciones son comúnmente usadas y admitidas por el enrutador de OpenShift para ajustar la Ruta generada:

Propósito Anotación Valores Típicos Efecto en la Ruta Generada
Terminación TLS route.openshift.io/termination edge · reencrypt · passthrough Establece spec.tls.termination de la Ruta al modo elegido.
Redirección HTTP→HTTPS (borde) route.openshift.io/insecureEdgeTerminationPolicy Redirect · Allow · None Controla spec.tls.insecureEdgeTerminationPolicy (comúnmente Redirect).
Balanceo de carga del backend haproxy.router.openshift.io/balance roundrobin · leastconn · source Establece el algoritmo de balanceo de HAProxy para la Ruta.
Timeout por ruta haproxy.router.openshift.io/timeout duración como 60s, 5m Configura el timeout de HAProxy para solicitudes en esa Ruta.
Cabecera HSTS haproxy.router.openshift.io/hsts_header por ejemplo, max-age=31536000;includeSubDomains;preload Inyecta la cabecera HSTS en las respuestas (borde/re-encriptar).

Nota: Las características avanzadas como backends ponderados/canario o hosts comodín no son expresables a través de Ingreso estándar. Usa una Ruta directamente para esos casos.

Ejemplo: Ingreso con anotaciones del enrutador de OpenShift

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress-https
  annotations:
    route.openshift.io/termination: edge
    route.openshift.io/insecureEdgeTerminationPolicy: Redirect
    haproxy.router.openshift.io/balance: leastconn
    haproxy.router.openshift.io/timeout: 60s
    haproxy.router.openshift.io/hsts_header: max-age=31536000;includeSubDomains;preload
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: test-service
            port:
              number: 80

Este Ingreso se realizará como una Ruta con TLS de borde y una redirección automática de HTTP→HTTPS, usando balanceo de menos conexiones y un timeout de ruta de 60s. La cabecera HSTS será añadida por el enrutador en las respuestas HTTPS.

Limitaciones de Usar Ingreso para Generar Rutas
Aunque conveniente, usar Ingreso para generar Rutas tiene limitaciones:

  • Falta de características avanzadas: Los backends ponderados y las sesiones persistentes requieren anotaciones específicas de Ruta y no son compatibles a través de Ingreso.
  • Modos de paso a través y re-encriptar TLS: Estos requieren anotaciones específicas de OpenShift en las Rutas y no son compatibles a través de Ingreso estándar.
  • Ingreso sin host: Un Ingreso sin un nombre de host no creará una Ruta; las Rutas requieren un host.
  • Hosts comodín: Los hosts comodín (por ejemplo, *.example.com) solo son compatibles a través de Rutas, no Ingreso.
  • Compatibilidad de anotaciones: Algunas anotaciones de Ruta de OpenShift no tienen equivalentes en Ingreso, lo que lleva a brechas de configuración.
  • Soporte de protocolo: Ingreso solo admite protocolos HTTP/HTTPS, mientras que las Rutas pueden manejar protocolos no HTTP con TLS de paso a través.
  • Riesgo de deriva de configuración: Debido a que las Rutas creadas a partir de Ingreso son gestionadas por OpenShift, las ediciones manuales a la Ruta generada pueden ser sobrescritas o causar inconsistencias.

Estas limitaciones significan que para configuraciones de enrutamiento avanzadas o características específicas de OpenShift, es preferible usar Rutas directamente.

Cuándo Usar Ingreso vs. Cuándo Usar Rutas
Elegir entre Ingreso y Rutas depende de tus requisitos:

  • Usa Ingreso si:
  • Quieres portabilidad entre plataformas de Kubernetes.
  • Tienes manifiestos de Ingreso existentes y quieres minimizar los cambios.
  • Tu aplicación usa solo enrutamiento básico HTTP o HTTPS.
  • Prefieres manifiestos neutrales a la plataforma para pipelines de CI/CD.
  • Usa Rutas si:
  • Necesitas características avanzadas de enrutamiento como backends ponderados, sesiones persistentes o múltiples modos de terminación TLS.
  • Tu implementación es específica de OpenShift y puede aprovechar las características nativas de OpenShift.
  • Requieres estabilidad y soporte completo para las capacidades de enrutamiento de OpenShift.
  • Necesitas exponer protocolos no HTTP o usar modos de paso a través/re-encriptar TLS.
  • Quieres usar hosts comodín o anotaciones personalizadas no compatibles con Ingreso.

En muchos casos, los equipos usan una combinación: Ingreso para portabilidad y Rutas para necesidades avanzadas o específicas de OpenShift.

Conclusión


En OpenShift, los recursos de Ingreso de Kubernetes se convierten automáticamente en Rutas, permitiendo la exposición básica de servicios externos con un esfuerzo mínimo. Esto permite a los usuarios aprovechar los manifiestos existentes de Kubernetes y mantener la portabilidad. Sin embargo, para escenarios de enrutamiento avanzados y para utilizar completamente las potentes características del Enrutador de OpenShift, se recomienda usar Rutas directamente.

Ambos, Ingreso y Rutas, coexisten sin problemas en OpenShift, permitiéndote elegir la herramienta adecuada para los requisitos de tu aplicación.

Using Kubernetes Ingress on OpenShift: How Routes Are Generated and When to Use Each

Introduction
OpenShift, Red Hat’s Kubernetes platform, has its own way of exposing services to external clients. In vanilla Kubernetes, you would typically use an Ingress resource along with an ingress controller to route external traffic to services. OpenShift, however, introduced the concept of a Route and an integrated Router (built on HAProxy) early on, before Kubernetes Ingress even existed. Today, OpenShift supports both Routes and standard Ingress objects, which can sometimes lead to confusion about when to use each and how they relate.

This article explores how OpenShift handles Kubernetes Ingress resources, how they translate to Routes, the limitations of this approach, and guidance on when to use Ingress versus Routes.

OpenShift Routes and the Router: A Quick Overview


OpenShift Routes are OpenShift-specific resources designed to expose services externally. They are served by the OpenShift Router, which is an HAProxy-based proxy running inside the cluster. Routes support advanced features such as:

  • Weighted backends for traffic splitting
  • Sticky sessions (session affinity)
  • Multiple TLS termination modes (edge, passthrough, re-encrypt)
  • Wildcard subdomains
  • Custom certificates and SNI
  • Path-based routing

Because Routes are OpenShift-native, the Router understands these features natively and can be configured accordingly. This tight integration enables powerful and flexible routing capabilities tailored to OpenShift environments.

Using Kubernetes Ingress in OpenShift (Default Behavior)


Starting with OpenShift Container Platform (OCP) 3.10, Kubernetes Ingress resources are supported. When you create an Ingress, OpenShift automatically translates it into an equivalent Route behind the scenes. This means you can use standard Kubernetes Ingress manifests, and OpenShift will handle exposing your services externally by creating Routes accordingly.

Example: Kubernetes Ingress and Resulting Route

Here is a simple Ingress manifest:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /testpath
        pathType: Prefix
        backend:
          service:
            name: test-service
            port:
              number: 80

OpenShift will create a Route similar to:

apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: example-route
spec:
  host: www.example.com
  path: /testpath
  to:
    kind: Service
    name: test-service
    weight: 100
  port:
    targetPort: 80
  tls:
    termination: edge

This automatic translation simplifies migration and supports basic use cases without requiring Route-specific manifests.

Tuning Behavior with Annotations (Ingress ➝ Route)

When you use Ingress on OpenShift, only OpenShift-aware annotations are honored during the Ingress ➝ Route translation. Controller-specific annotations for other ingress controllers (e.g., nginx.ingress.kubernetes.io/*) are ignored by the OpenShift Router. The following annotations are commonly used and supported by the OpenShift router to tweak the generated Route:

Purpose Annotation Typical Values Effect on Generated Route
TLS termination route.openshift.io/termination edge · reencrypt · passthrough Sets Route spec.tls.termination to the chosen mode.
HTTP→HTTPS redirect (edge) route.openshift.io/insecureEdgeTerminationPolicy Redirect · Allow · None Controls spec.tls.insecureEdgeTerminationPolicy (commonly Redirect).
Backend load-balancing haproxy.router.openshift.io/balance roundrobin · leastconn · source Sets HAProxy balancing algorithm for the Route.
Per-route timeout haproxy.router.openshift.io/timeout duration like 60s, 5m Configures HAProxy timeout for requests on that Route.
HSTS header haproxy.router.openshift.io/hsts_header e.g. max-age=31536000;includeSubDomains;preload Injects HSTS header on responses (edge/re-encrypt).

Note: Advanced features like weighted backends/canary or wildcard hosts are not expressible via standard Ingress. Use a Route directly for those.

Example: Ingress with OpenShift router annotations

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress-https
  annotations:
    route.openshift.io/termination: edge
    route.openshift.io/insecureEdgeTerminationPolicy: Redirect
    haproxy.router.openshift.io/balance: leastconn
    haproxy.router.openshift.io/timeout: 60s
    haproxy.router.openshift.io/hsts_header: max-age=31536000;includeSubDomains;preload
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: test-service
            port:
              number: 80

This Ingress will be realized as a Route with edge TLS and an automatic HTTP→HTTPS redirect, using least connections balancing and a 60s route timeout. The HSTS header will be added by the router on HTTPS responses.

Limitations of Using Ingress to Generate Routes
While convenient, using Ingress to generate Routes has limitations:

  • Missing advanced features: Weighted backends and sticky sessions require Route-specific annotations and are not supported via Ingress.
  • TLS passthrough and re-encrypt modes: These require OpenShift-specific annotations on Routes and are not supported through standard Ingress.
  • Ingress without host: An Ingress without a hostname will not create a Route; Routes require a host.
  • Wildcard hosts: Wildcard hosts (e.g., *.example.com) are only supported via Routes, not Ingress.
  • Annotation compatibility: Some OpenShift Route annotations do not have equivalents in Ingress, leading to configuration gaps.
  • Protocol support: Ingress supports only HTTP/HTTPS protocols, while Routes can handle non-HTTP protocols with passthrough TLS.
  • Config drift risk: Because Routes created from Ingress are managed by OpenShift, manual edits to the generated Route may be overwritten or cause inconsistencies.

These limitations mean that for advanced routing configurations or OpenShift-specific features, using Routes directly is preferable.

When to Use Ingress vs. When to Use Routes
Choosing between Ingress and Routes depends on your requirements:

  • Use Ingress if:
  • You want portability across Kubernetes platforms.
  • You have existing Ingress manifests and want to minimize changes.
  • Your application uses only basic HTTP or HTTPS routing.
  • You prefer platform-neutral manifests for CI/CD pipelines.
  • Use Routes if:
  • You need advanced routing features like weighted backends, sticky sessions, or multiple TLS termination modes.
  • Your deployment is OpenShift-specific and can leverage OpenShift-native features.
  • You require stability and full support for OpenShift routing capabilities.
  • You need to expose non-HTTP protocols or use TLS passthrough/re-encrypt modes.
  • You want to use wildcard hosts or custom annotations not supported by Ingress.

In many cases, teams use a combination: Ingress for portability and Routes for advanced or OpenShift-specific needs.

Conclusion


On OpenShift, Kubernetes Ingress resources are automatically converted into Routes, enabling basic external service exposure with minimal effort. This allows users to leverage existing Kubernetes manifests and maintain portability. However, for advanced routing scenarios and to fully utilize OpenShift’s powerful Router features, using Routes directly is recommended.

Both Ingress and Routes coexist seamlessly on OpenShift, allowing you to choose the right tool for your application’s requirements.