Expose basepath in container through service in nginx ingress on kubernetes

11/2/2020

My ASP.NET Core web application uses basepath in startup like,

app.UsePathBase("/app1");

So the application will run on basepath. For example if the application is running on localhost:5000, then the app1 will be accessible on 'localhost:5000/app1'.

So in nginx ingress or any ingress we can expose the entire container through service to outside of the kubernetes cluster.

My kubernetes deployment YAML file looks like below,

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app1-deployment
spec:
  selector:
    matchLabels:
      app: app1
  replicas: 1
  template:
    metadata:
      labels:
        app: app1
    spec:
      containers:
      - name: app1-container
        image: app1:latest
        ports:
        - containerPort: 5001
---
apiVersion: v1
kind: Service
metadata:
  name: app1-service
  labels:
    app: app1
spec:
  type: NodePort
  ports:
  - name: app1-port
    port: 5001
    targetPort: 5001
    protocol: TCP
  selector:
    app: app1
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: app1-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
  - http:
      paths:
      - path: /app1(/|$)(.*)
        backend:
          serviceName: server-service
          servicePort: 5001

The above ingress will expose the entire container in 'localhost/app1' URL. So the application will run on '/app1' virtual path. But the app1 application will be accessible on 'localhost/app1/app1'.

So I want to know if there is any way to route 'localhost/app1' request to basepath in container application 'localhost:5001/app1' in ingress.

-- Sesha3
docker
kubernetes
kubernetes-ingress
nginx
nginx-ingress

1 Answer

11/3/2020

If I understand correctly, now the app is accessible on /app1/app1 and you would like it to be accessible on /app1

To do this, don't use rewrite:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: app1-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - http:
      paths:
      - path: /app1
        backend:
          serviceName: server-service
          servicePort: 5001
-- Matt
Source: StackOverflow