如何在 Kubernetes 中暴露 MariaDB?

How to expose MariaDB in Kubernetes?

我在 Microk8s 中有一个带有 MariaDB 运行 的 Docker 容器(运行 在一台 Unix 机器上)。

# Hello World Deployment YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mariadb
spec:
  selector:
    matchLabels:
      app: mariadb
  template:
    metadata:
      labels:
        app: mariadb
    spec:
      containers:
      - name: mariadb
        image: mariadb:latest
        env:
        - name: MARIADB_ROOT_PASSWORD
          value: sa
        ports:
        - containerPort: 3306

这些是日志:

(...)
2021-09-30  6:09:59 0 [Note] mysqld: ready for connections.
Version: '10.6.4-MariaDB-1:10.6.4+maria~focal'  socket: '/run/mysqld/mysqld.sock'  port: 3306  mariadb.org binary distribution

现在,

如何连接?

答案已写在评论部分,但为了澄清,我将解决方案作为社区 Wiki 发布在这里。

在这种情况下,连接问题已通过设置 spec.selector 得到解决。

The .spec.selector field defines how the Deployment finds which Pods to manage. In this case, you select a label that is defined in the Pod template (app: nginx).

.spec.selector is a required field that specifies a label selector for the Pods targeted by this Deployment.

您需要使用带有适当标签的服务

示例服务

apiVersion: v1
kind: Service
metadata:
  name: mariadb
spec:
  selector:
    name: mariadb
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306
  type: ClusterIP

您可以使用服务名称进行连接,或者将服务类型更改为 LoadBalancer 以使用 IP 公开它。

apiVersion: v1
kind: Service
metadata:
  name: mariadb
spec:
  selector:
    name: mariadb
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306
  type: LoadBalancer