Kubernetes do I need to include port when directing?

11/3/2019

I have an application running in K8s. It has 3 microservices and nginx in front of them. Each redirection goes through nginx first and is proxied as specified. My flask app is having issues redirecting without the port number. I run k8s locally via minikube. Whenever I redirect to another page the url doesn't include port number, which throws me an error.

if usernamedata == None:
    print("Could not log in")   
else:
    if passworddata == password:
        print("Logged in")
        return redirect("/user/{0}".format(username))

Nginx is the only service exposed and its url is http://192.168.99.107:31699 With my redirection in flask I get redirected to http://192.168.99.107/user/David, which throws me connection refused. If I add port number and make it http://192.168.99.107:31699/user/David it works fine. Do I need to specify port number when redirecting? What if the service is down and recreated? Also, this is my service definition for nginx:

kind: Service
apiVersion: v1
metadata:
  name: nginx
  labels:
    svc: nginx
spec:
  selector:
    app:  nginx-app
  type: LoadBalancer
  ports:
   - port:  80

How can I make redirection within flask app work?

-- davidb
flask
kubernetes
nginx

1 Answer

11/3/2019

If service is down and recreated and you want to retain same high port number for your service you need to specify nodePort and change type of service to NodePort.

apiVersion: v1
kind: Service
metadata:
  name: my-service
  labels:
    svc: nginx
spec:
  type: NodePort # type is set to NodePort
  ports:
  - port: 80 # Service's internal cluster IP
    targetPort: 80 # target port of the backing pods
    nodePort: 31699 # service will be only available via this port for each cluster node if recreated
  selector:
    app:  nginx-app

Within your Python code (If Service starts before Pod):

import os 

...
service_host = os.environ.get("NGINX_SERVICE_HOST")
service_port = os.environ.get("NGINX_SERVICE_PORT")
...
redirect(f"http://{service_host}:{service_port}/user/{username}")
-- fg78nc
Source: StackOverflow