Containerize a MySQL database using Kubernetes

Filed Under: Random
Containerize A MySQL Database Using Kubernetes

Hello, readers! This article talks about the Practical Implementation to Containerize a MySQL database using Kubernetes as the base. So, let us begin!! 馃檪


Practical Implementation to Containerize a MySQL database

For ages, we have been using some way to store huge data of any processes or events within the organization. We have seen the transition from on-premises data centers to database software and now to the cloud as a database.

This article talks about optimizing the process of data storage through containerizing the MySQL database over the cloud using Kubernetes.

Containerizing a MySQL database gives us the access to use a MySQL database as a container within any application over Kubernetes infrastructure. Also, we can perform the same heavy, complex queries and operations within the MySQL database container as any other client database software.

Containerizing a MySQL database involves the below steps-

  1. A Kubernetes Service that the MySQL pod listens
  2. Kubernetes Secret to store the MySQL credentials
  3. Kubernetes Deployment to containerize a MySQL instance
  4. Persistent Volume to store the data generated within the container
  5. Persistent Volume claim in order to claim the PV created in step 4.

Let us now have a look at the above steps one by one in detail.


1. Create a Service for the database to listen

If we wish to have access to the MySQL database through a client software, we can make use of NodePort service which makes our MySQL database (container) accessible through MySQL client software or workbench.

Have a look at the below code –

apiVersion: v1
kind: Service
metadata:
  name: demo-mysql-nodeport
  labels:
    app: demo
spec:
  type: NodePort
  ports:
    - port: 3306
  selector:
    app: demo

The above YAML file creates a NodePort type Kubernetes service in the cluster and enables us to access the database from outside the cluster network using the NodePort that gets assigned to this service.

The MySQL database container would be listening to the instructions from this service by matching the labels and selector’s values.


2. Create Kubernetes Secret for MySQL credentials

For us to access the database as a container, we need the have the details around the Username and Password of the database.

We can store the database Username and Password as a Kubernetes Secret and refer it within the Container deployment file to access the DB.

Have a look at the below code-

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: kubernetes.io/basic-auth
stringData:
  username: mymysql
  password: t0p-Secret-123@@#$

We can now use this secret within the deployment file for it to accept these values as the authorized credentials to access the database.


3. Create a Persistent Volume to store the Stateful data

Have a look at the below code snippet-

apiVersion: v1
kind: PersistentVolume
metadata:
  name: demopv
  labels:
    app: demo
spec:
  storageClassName: ""
  capacity:
    storage: 20Gi
  accessModes:
    - ReadWriteOnce

Here, we create a Persistent Volume of size 20Gi to store the data through the MySQL container dynamically.


4. Create a Persistent Volume Claim for the PV

In order to access the above created Persistent Volume, we need to create a Persistent volume claim for us to claim the storage for the container’s use.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: demopvc
spec:
  storageClassName: ""
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi

5. Create a MySQL deployment

The last and final step is to create a MySQL deployment file for us to make use of the persistent volume for storage as well as the secret for the credentials.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: demo-mysql
  labels:
    app: demo
spec:
  selector:
    matchLabels:
      app: demo
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - image: mysql:5.6
        resources:
            limits: 
              cpu: 100m
              memory: 1Gi
            requests:
              cpu: 60m
              memory: 500Mi
        name: mysql
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysecret
              key: password
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: demopv
          mountPath: /var/lib/mysql 
      volumes:
      - name: demopv
        persistentVolumeClaim:
          claimName: demopvc

kubectl apply -f mysql.yaml

Inspecting the MySQL database as a Container

Having created the MySQL container now is the time to inspect it for use.

kubectl describe deploy demo-mysql

Output-

Name:                 demo-mysql
 Namespace:            default
 Labels:               app=demo
 Annotations:          deployment.kubernetes.io/revision=1
 Selector:             app=demo
 Replicas:             1 desired | 1 updated | 1 total | 0 available | 1 unavailable
 StrategyType:         Recreate
 MinReadySeconds:      0
 Pod Template:
   Labels:       app=demo
   Containers:
    mysql:
     Image:      mysql:5.6
     Port:       3306/TCP
     Environment:
       MYSQL_ROOT_PASSWORD:      password
     Mounts:
       /var/lib/mysql from mysql-persistent-storage (rw)
   Volumes:
    mysql-persistent-storage:
     Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
     ClaimName:  demopvc
     ReadOnly:   false
 Conditions:
   Type          Status  Reason
   ----          ------  ------
   Available     False   MinimumReplicasUnavailable
   Progressing   True    ReplicaSetUpdated
 OldReplicaSets:       <none>
 NewReplicaSet:        mysql-63082529 (1/1 replicas created)
 Events:
   FirstSeen    LastSeen    Count    From                SubobjectPath    Type        Reason            Message
   ---------    --------    -----    ----                -------------    --------    ------            -------
   33s          33s         1        {deployment-controller }             Normal      ScalingReplicaSet Scaled up replica set mysql-63082529 to 1

In order to get into the MySQL database, we can exec into the MySQL container and log in using the credentials stored as a Secret-

kubectl exec -it mysql -- sh

Output-

/#

Here we can execute the command to login into the MySQL database as shown below-

mysql -h username -p password

Output-

mysql>


Conclusion

By this, we have reached the end of this topic. Feel free to comment below, in case you come across any questions.

For more such posts related to Kubernetes, Stay tuned with us.

Till then, Happy Learning!! 馃檪

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content