How to expose MariaDB in Kubernetes?

9/30/2021

I have a Docker container with MariaDB running in Microk8s (running on a single Unix machine).

# 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

These are the logs:

(...)
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

Now,

  • connecting to port 3306 on the machine does not work.
  • connecting after exposing the pod with a service (any type) on port 8081 also does not work.

How can I get the connection through?

-- DomJourneyman
docker
kubernetes
mariadb
yaml

2 Answers

10/14/2021

You need to use the service with proper label

example service

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

you can use the service name to connect or else change the service type as LoadBalancer to expose it with IP.

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

10/14/2021

The answer has been written in comments section, but to clarify I am posting here solution as Community Wiki.

In this case problem with connection has been resolved by setting 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.

-- kkopczak
Source: StackOverflow