How to connect MySQL running on Kubernetes

2019-06-23 16:12发布

问题:

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

回答1:

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.



回答2:

To add to the above answer, when you add --address 0.0.0.0 kubectl should open 3306 port to the INTERNET too (not only localhost)!

kubectl port-forward POD_NAME 3306:3306 --address 0.0.0.0

Use it with caution for short debugging sessions only, on development systems at most. I used it in the following situation:

  • colleague who uses Windows
  • didn't have ssh key ready
  • environment was a playground I was not afraid to expose to the world


回答3:

You need to enable remote access on your MySQL server. See this link on how to enable remote access on MySQL server: http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html