Conecting to a specific pod inside a statefulset from outside the cluster

12/11/2019

I have a StatefulSet that matchs the one described in the StatefulSet Kubernetes tutorial which creates a mysql master/slaves structure. I have the following kubernetes objects:

    NAME          READY   STATUS    RESTARTS   AGE
pod/mysql-0   2/2     Running   7          23h
pod/mysql-1   2/2     Running   6          23h
pod/mysql-2   2/2     Running   6          23h

NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
service/kubernetes   ClusterIP   10.152.183.1    <none>        443/TCP    21d
service/mysql        ClusterIP   None            <none>        3306/TCP   23h
service/mysql-read   ClusterIP   10.152.183.89   <none>        3306/TCP   23h

NAME                     READY   AGE
statefulset.apps/mysql   3/3     23h

EDIT: The mysql and mysql-read services connect with all the mysql pods.

The node is on my computer, I'm using microk8s.

Now I have a little program runnning on my computer (not in the cluster) that I would like to connect to the master (mysql-0) inside the StatefulSet. Id need something like a service that only connect with mysql-0. Any suggestions on how to do it?

EDIT: The idea is to find a solution that allow me to deploy the cluster just with the .yaml files. It isn't interesting to find one that involves more commands than kubectl apply

The program is the following one:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost??",
  user="root",
  passwd="",
  database="testtable"
)

mycursor = mydb.cursor()

sql = "INSERT INTO testtable (name) VALUES (%s)"
val = ("holaquetal")
mycursor.execute(sql, val)

mydb.commit()

I thought I could add a different label to the mysql-0 pod and add a NodePort service that looks for that label, but I dont want to do it by command line. Is it possible to add one label to mysql-0 inside the StatefulSet yaml?

Another idea could be to do a query DNS to the DNS server that microk8s provides, looking for "mysql.mysql-0", but I don't know how to connect the program to the DNS server, so that I can use host=mysql.mysql-0 or the whole CNAME.

-- Manu Ruiz Ruiz
kubernetes

1 Answer

12/11/2019

If the node is on your computer so can use port-forward to forward the port of mysql from the pod to your local. Try this:

kubectl port-forward mysql-0 3306:3306

or forward directly to your master service

kubectl port-forward svc/mysql-read 3306:3306

-- hxquangnhat
Source: StackOverflow