Creating HTTP/S Routing Rules Programmatically
We understand the structure of the Ingress
resource and the necessity of an Ingress Controller. Now, let's use client-go
to define the core routing logic – the rules that map incoming hostnames and paths to backend Kubernetes Services.
This involves constructing the networkingv1.Ingress
Go struct, paying close attention to the spec.rules
and spec.tls
fields, and then using the client-go
clientset to create this resource in the cluster.
Constructing the Ingress
Struct in Go
Let's build an example where we want to achieve the following routing:
Requests to
app.example.com/login
should go tologin-service
on its named porthttp
.Requests to
app.example.com/api/users
should go touser-api-service
on port8080
.Requests to
metrics.example.com/
should go tometrics-service
on port9090
.Enable TLS for
app.example.com
using a Secret namedapp-tls-secret
.
First, we need to import the necessary packages, including k8s.io/api/networking/v1
. Then, we construct the Ingress
object in Go:
Key Go Constructs:
Import
networking/v1
: We usek8s.io/api/networking/v1
.IngressClassName
: Crucial for directing the resource to the correct controller.Rules
Slice: We create a slice ofnetworkingv1.IngressRule
.Host
: Set the target hostname within each rule.HTTP
andPaths
: We define theHTTPIngressRuleValue
and itsPaths
slice ([]networkingv1.HTTPIngressPath
).Path
andPathType
: Specify the URL path and how it should be matched (e.g.,Prefix
). Note thatPathType
requires a pointer, so we assign&pathTypePrefix
.Backend
andService
: Define the targetService
usingnetworkingv1.IngressBackend
andnetworkingv1.IngressServiceBackend
.Service Port (Name vs. Number)
: We specify the target port on the Service using eitherPort.Name
orPort.Number
.TLS
Slice: We define a slice ofnetworkingv1.IngressTLS
.Hosts
andSecretName
: Link the hostnames to the Kubernetes Secret containing the certificate and key. Prerequisite: The Secret (app-tls-secret
in this case) must exist in the same namespace and be of typekubernetes.io/tls
.Create
Call: We useclientset.NetworkingV1().Ingresses(namespace).Create(...)
to submit the definedIngress
object to the API server.
By constructing these Ingress
objects programmatically, you gain the ability to automate the exposure of your applications, potentially integrating with CI/CD pipelines, service discovery systems, or custom dashboards to manage external access dynamically based on application lifecycle events or other triggers.
Last updated
Was this helpful?