Dynamic URL for Host using OpenShift routes

Did you know that in OpenShift, you can use Route objects to simply define the prefix for the host url and that the route will automatically fill in the cluster context as the suffix.

Let’s say you have an application called “app1” and it’s going to be in three different clusters – dev, test, prod – with three different cluster suffix. In the dev environment, you would want the URL to be “app1.dev.ocp.yourcompany.com” and of course change the values for the other environments.

You can do that with the Route using the subdomain value in the spec. Here’s a full example.

apiVersion: v1
kind: Namespace
metadata:
  name: busybox-http
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: busybox-http-web-content
  namespace: busybox-http
  labels:
    app: busybox-http
data:
  index.html: |
    <!DOCTYPE html>
    <html>
    <head>
        <title>BusyBox Web Server</title>
    </head>
    <body>
        <h1>Hello from the OpenShift BusyBox Web Server!</h1>
    </body>
    </html>
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: busybox-http
  namespace: busybox-http
  labels:
    app: busybox-http
spec:
  replicas: 1
  selector:
    matchLabels:
      app: busybox-web
  template:
    metadata:
      labels:
        app: busybox-web
    spec:
      containers:
      - name: busybox-container
        image: busybox:latest
        command: ["/bin/sh", "-c", "httpd -f -p 8080 -h /var/www/html"]
        ports:
        - containerPort: 8080
        volumeMounts:
        - name: web-content-volume
          mountPath: /var/www/html
      volumes:
      - name: web-content-volume
        configMap:
          name: busybox-http-web-content
---
apiVersion: v1
kind: Service
metadata:
  name: busybox-http
  namespace: busybox-http
  labels:
    app: busybox-http
spec:
  selector:
    app: busybox-web
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 8080
---
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: busybox-http
  namespace: busybox-http
  labels:
    app: busybox-http
spec:
  subdomain: busybox
  to:
    kind: Service
    name: busybox-http
    weight: 100
  port:
    targetPort: 8080
  tls:
    termination: edge
    insecureEdgeTerminationPolicy: Redirect
  wildcardPolicy: None

This creates a route to https://busybox.apps.<cluster_suffix>in any environment.