Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect MySQL running on Kubernetes

I have deployed my application on Google gcloud container engine. My application required MySQL. Application is running fine and connecting to MySQL correctly. But I want to connect MySQL database from my local machine using MySQL Client (Workbench, or command line), Can some one help me how to expose this to local machine? and how can I open MySQL command line on gcloud shell ?

I have run below command but external ip is not there :

$ kubectl get deployment
NAME           DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
app-mysql   1         1         1            1           2m
$ kubectl get pods
NAME                            READY     STATUS             RESTARTS   AGE
app-mysql-3323704556-nce3w   1/1       Running            0          2m
$ kubectl get service
NAME           CLUSTER-IP    EXTERNAL-IP       PORT(S)    AGE
app-mysql   11.2.145.79   <none>            3306/TCP   23h

EDIT

I am using below yml file:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: app-mysql
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: app-mysql
    spec:
      volumes:
      - name: data
        emptyDir: {}
      containers:
      - name: mysql
        image: mysql:5.6.22
        env:
        - name: MYSQL_USER
          value: root
        - name: MYSQL_DATABASE
          value: appdb
        ports:
        - containerPort: 3306
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql/
---
apiVersion: v1
kind: Service
metadata:
  name: app-mysql
spec:
  selector:
    app: app-mysql
  ports:
  - port: 3306
like image 882
Anchit Pancholi Avatar asked Oct 07 '16 05:10

Anchit Pancholi


2 Answers

Try the kubectl port-forward command.

In your case; kubectl port-forward app-mysql-3323704556-nce3w 3306:3306

See The documentation for all available options.

like image 173
Tim Avatar answered Sep 25 '22 20:09

Tim


There are 2 steps involved:

1 ) You first perform port forwarding from localhost to your pod:

kubectl port-forward <your-mysql-pod-name> 3306:3306 -n <your-namespace>

2 ) Connect to database:

mysql -u root -h 127.0.0.1 -p <your-password>
 

Notice that you might need to change 127.0.0.1 to localhost - depends on your setup.

If host is set to:
localhost - then a socket or pipe is used.
127.0.0.1 - then the client is forced to use TCP/IP.

You can check if your database is listening for TCP connections with netstat -nlp.


Read more in:

Cant connect to local mysql server through socket tmp mysql sock

Can not connect to server

like image 40
RtmY Avatar answered Sep 23 '22 20:09

RtmY