Cannot connect to Mysql service from c# front-end in kubernetes

7/12/2019

I have a kubernetes cluster with front end as C# console application written in .NET Core and a backend Mysql db. Both of these applications are deployed as deployments in kubernetes in different pods. I have also created a mysql service to be able to connect with Mysql db. But, I can't seem to connect to mysql server from .NET core console app to kubernetes Mysql service. However, I can pretty much connect with Mysql pod using the IP address from the console app.

I will try my best to describe the situation here.

$ kubectl -n radiomicsapp get pods -o wide
NAME                                                          READY     STATUS    RESTARTS   AGE       IP             NODE
anonymizer-pod-586548ddd9-kv8cj                               2/2       Running   0          21s       10.244.0.187   aks-agentpool-35971152-1
mysql-744bfb878c-scwz9                                        1/1       Running   0          19h       10.244.1.244   aks-agentpool-35971152-2

$ kubectl -n abcapp get svc
NAME                                         TYPE           CLUSTER-IP     EXTERNAL-IP      PORT(S)                      AGE
mysql                                        ClusterIP      10.0.54.120    <none>           3306/TCP                     104d

If I use IP address from the pod (10.244.1.244) to connect with db, it works. However, if I use IP address (10.0.54.120) from mysql service, it throws

Error: Unable to connect to any of the specified MySQL hosts.

Since, the IP address of the mysql pod changes whenever the pod is restarted/recreated, I will have to change the db connection string in my anonymizer console app, I created a mysql service with type ClusterIP as given below:

apiVersion: v1
kind: Service
metadata:
   name: mysql
   namespace: abcapp
   labels:
    app: abc
spec:
   type: ClusterIP
   ports:
     - name: mysql
       port: 3306
       protocol: TCP
       targetPort: 3306
   selector:
     app: abc

Also, my anonymizer pod, mysql pod as well as mysql service are all in the same namespace.

Any help would be much appreciated. Thanks for taking your time.

-- Binay
c#
kubectl
kubernetes
mysql

1 Answer

7/12/2019

You have to use the service name on your code and leave kube-dns to handle the IP resolution for you to be sure your code works no matter if the pod is recreated or moved and it takes a different IP address during the process.

From another answer is easy to extrapolate an approximate example

How to connect to MySQL Database?

string connstring = string.Format("Server=mysql; database={0}; UID=UserName; password=your password", databaseName);
connection = new MySqlConnection(connstring);

Notice that only need to put on the Server mysql

-- wolmi
Source: StackOverflow