如何在Kubernetes上访问MySQL即服务?

时间:2019-07-14 20:28:57

标签: mysql kubernetes

我有以下部署...

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-data-disk
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql-deployment
  labels:
    app: mysql
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - name: mysql
          image: mysql:5.7
          ports:
            - containerPort: 3306
          volumeMounts:
            - mountPath: "/var/lib/mysql"
              subPath: "mysql"
              name: mysql-data
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-secrets
                  key: ROOT_PASSWORD
      volumes:
        - name: mysql-data
          persistentVolumeClaim:
            claimName: mysql-data-disk

这很好用,我可以像这样访问数据库...

kubectl exec -it mysql-deployment-<POD-ID> -- /bin/bash

然后我跑...

mysql -u root -h localhost -p

我可以登录。但是,当我尝试使用以下yaml将其作为服务访问时...

---
apiVersion: v1
kind: Service
metadata:
  name: mysql-service
spec:
  selector:
    app: mysql
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306

我可以通过运行此kubectl describe service mysql-service看到它。

Name:              mysql-service
Namespace:         default
Labels:            <none>
Annotations:       kubectl.kubernetes.io/last-applied-configuration:
                     {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"name":"mysql-service","namespace":"default"},"spec":{"ports":[{"port":33...
Selector:          app=mysql
Type:              ClusterIP
IP:                10.101.1.232
Port:              <unset>  3306/TCP
TargetPort:        3306/TCP
Endpoints:         172.17.0.4:3306
Session Affinity:  None
Events:            <none>

然后我通过运行kubectl cluster-info

#kubectl cluster-info
Kubernetes master is running at https://192.168.99.100:8443
KubeDNS is running at https://192.168.99.100:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

但是当我尝试使用Oracle SQL Developer这样连接时...

enter image description here

它说无法连接。

enter image description here

如何连接到在K8s上运行的MySQL?

2 个答案:

答案 0 :(得分:3)

服务类型ClusterIP将无法在Pod网络外部访问。 如果没有LoadBalancer选项,则必须使用服务类型NodePortkubectl port-forward

答案 1 :(得分:1)

  1. 您需要mysql服务的类型为NodePort而不是ClusterIP才能在Kubernetes之外访问它。

  2. 在客户端配置中使用节点端口

示例服务:

apiVersion: v1
kind: Service
metadata:
  name: mysql-service
spec:
  type: NodePort
  selector:
    app: mysql
  ports:
    - protocol: TCP
      port: 3306
      nodePort: 30036
      targetPort: 3306

因此,您可以在客户端中使用端口:30036。