How to expose an "election-based master and secondaries" service outside Kubernetes cluster?

3/28/2018

I've been trying to implement a service inside Kubernetes where each Pod needs to be accessible from outside the Cluster.

The topology of my service is simple: 3 members, one of them acting as master at any time (election based); writes go to primary; reads go to secondaries. This is MongoDB replica set by the way.

They work with no issues inside the Kubernetes cluster, but from outside the only thing I have is a NodePort service type that load balances incoming connections to one of them, but I need to access each on of them, separately, depending on what I want to do from my client (write or read).

What kind of Kubernetes resource should I use to give individual access to each one of the members of my service?

-- licorna
kubernetes
mongodb

1 Answer

3/29/2018

In order to access every pod from outside you can create a separate service for each pod and use NodePort type.

Because Service uses selectors to get to available backends, you can create just one Service for a master:

apiVersion: v1
kind: Service
metadata:
  name: my-master
  labels:
    run: my-master
spec:
  type: NodePort
  ports:
  - port: #your-external-port
    targetPort: #your-port-exposed-in-pod
    protocol: TCP
  selector:
    run: my-master
-------------
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-master
spec:
  selector:
    matchLabels:
      run: my-master
  replicas: 1
  template:
    metadata:
      labels:
        run: my-master
    spec:
      containers:
      - name: mongomaster
        image: yourcoolimage:lates
        ports:
        - containerPort: #your-port-exposed-in-pod

Also, you can use one Service for all your read-only replicas and this service will balance requests between all of them.

apiVersion: v1
kind: Service
metadata:
  name: my-replicas
  labels:
    run: my-replicas
spec:
  type: LoadBalancer
  ports:
  - port: #your-external-port
    targetPort: #your-port-exposed-in-pod
    protocol: TCP
  selector:
    run: my-replicas

---------

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-replicas
spec:
  selector:
    matchLabels:
      run: my-replicas
  replicas: 2
  template:
    metadata:
      labels:
        run: my-replicas
    spec:
      containers:
      - name: mongoreplica
        image: yourcoolimage:lates
        ports:
        - containerPort: #your-port-exposed-in-pod

I also suggest you do not expose Pod outside of your network because of security reasons. It would be better to create strict firewall rules to restrict any unexpected connections.

-- Nick Rak
Source: StackOverflow