Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 78 ยท Projects

Project: WordPress and MySQL with PersistentVolumes

Deploy WordPress with MySQL on Kubernetes: Secret, StatefulSet with a volume claim, WordPress Deployment with a PVC, Services, Ingress, probes and backups.

WordPress with MySQL is the classic stateful application: a PHP web tier that is easy to replace, and a database plus uploaded files that you must never lose. That makes it a perfect second project after the web app with a database. This time two things have to survive a Pod restart (the database and wp-content, where uploads, themes and plugins live), and you will see why that changes how you roll out updates.

You will write a namespace, a Secret, a MySQL StatefulSet with its own volume, a WordPress Deployment with a PersistentVolumeClaim, two Services and an Ingress, then learn how to check it, back it up and clean it up. There is no cluster on this site, so the manifests and kubectl commands are read-only. What was run for this lesson: both container images in Docker with exactly the environment variables used below (MySQL 8.4 and the official wordpress image), which showed that WordPress connects to MySQL and serves its installation page. The Kubernetes behavior is read-only, and the two runnable examples are Python models.

The plan

flowchart LR
  user["Browser"] --> ing["Ingress<br/>blog.example.test"]
  ing --> wsvc["Service wordpress :80"]
  wsvc --> wp["Deployment wordpress<br/>1 replica"]
  wp --> wpvc[("PVC wp-content 2Gi")]
  wp -->|"mysql-0.mysql :3306"| db["StatefulSet mysql"]
  db --> dvc[("PVC data-mysql-0 5Gi")]
  sec["Secret blog-db"] -.-> wp
  sec -.-> db

Both tiers read their credentials from one Secret; each stateful part gets its own PersistentVolumeClaim.

Related lessons: Secrets, StatefulSets, Persistent Volumes, Storage Classes, Ingress, Probes.

Step 1: Namespace and Secret

A namespace keeps everything together and easy to delete (Namespaces and Quotas). The Secret holds the database settings so that the MySQL image and the WordPress image read the same values.

YAML
# 00-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: blog
---
# 01-secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: blog-db
  namespace: blog
type: Opaque
stringData:
  MYSQL_ROOT_PASSWORD: change-this-root-password
  MYSQL_DATABASE: wordpress
  MYSQL_USER: wp
  MYSQL_PASSWORD: change-this-wp-password

stringData lets you write plain text, and Kubernetes stores it base64-encoded, which is encoding, not encryption. Do not commit real passwords to Git: create the Secret from the command line, with a sealed-secrets or external-secrets tool, or from your CI system (External Secrets and Config Patterns):

Terminal
kubectl create namespace blog
kubectl create secret generic blog-db -n blog \
  --from-literal=MYSQL_ROOT_PASSWORD="$(openssl rand -base64 24)" \
  --from-literal=MYSQL_DATABASE=wordpress \
  --from-literal=MYSQL_USER=wp \
  --from-literal=MYSQL_PASSWORD="$(openssl rand -base64 24)"

Step 2: MySQL as a StatefulSet

A database needs a stable identity and its own storage. A StatefulSet gives the Pod a fixed name (mysql-0) and creates a PersistentVolumeClaim for it from a volume claim template. That claim is not deleted when the Pod is deleted or rescheduled, so the data follows the Pod name.

YAML
# 02-mysql.yaml
apiVersion: v1
kind: Service
metadata:
  name: mysql
  namespace: blog
spec:
  clusterIP: None            # headless: DNS returns the Pod address directly
  selector:
    app: mysql
  ports:
    - name: mysql
      port: 3306
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
  namespace: blog
spec:
  serviceName: mysql
  replicas: 1
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - name: mysql
          image: mysql:8.4
          ports:
            - containerPort: 3306
          envFrom:
            - secretRef:
                name: blog-db
          volumeMounts:
            - name: data
              mountPath: /var/lib/mysql
              subPath: mysql
          resources:
            requests:
              cpu: 250m
              memory: 512Mi
            limits:
              memory: 1Gi
          readinessProbe:
            exec:
              command: ["sh", "-c", "mysqladmin ping -h 127.0.0.1 -uroot -p\"$MYSQL_ROOT_PASSWORD\""]
            initialDelaySeconds: 15
            periodSeconds: 10
          livenessProbe:
            exec:
              command: ["sh", "-c", "mysqladmin ping -h 127.0.0.1 -uroot -p\"$MYSQL_ROOT_PASSWORD\""]
            initialDelaySeconds: 60
            periodSeconds: 20
            failureThreshold: 6
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 5Gi

Decisions worth understanding:

  • Headless Service (clusterIP: None) is required by a StatefulSet (serviceName). It gives every Pod a DNS name: mysql-0.mysql.blog.svc.cluster.local. WordPress will use that exact name.
  • envFrom with a Secret turns every key in blog-db into an environment variable. The official MySQL image reads MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER and MYSQL_PASSWORD on its first start and creates the database and user.
  • subPath: mysql mounts a subdirectory of the volume. Many volume types contain a lost+found folder at their root, and MySQL refuses to initialize a data directory that is not empty. A subdirectory avoids that.
  • Only one replica. A StatefulSet of MySQL with replicas: 3 would start three independent, unreplicated databases. Real replication needs an operator or a managed database, which is the better choice for production (Stateful Apps and Backups, Custom Resources and Operators).
  • Probes call mysqladmin ping, using the password from the environment. The liveness delay is long on purpose: a restart during initialization or crash recovery can make things worse.
  • Memory limit, no CPU limit. A requests-and-limits baseline lets the scheduler place the Pod, and a memory ceiling protects the node (Resource Requests and Limits).

Step 3: WordPress, its volume and its Service

YAML
# 03-wordpress.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: wp-content
  namespace: blog
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 2Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: wordpress
  namespace: blog
spec:
  replicas: 1
  strategy:
    type: Recreate           # a ReadWriteOnce volume can only be attached to one node at a time
  selector:
    matchLabels:
      app: wordpress
  template:
    metadata:
      labels:
        app: wordpress
    spec:
      containers:
        - name: wordpress
          image: wordpress:6-apache
          ports:
            - containerPort: 80
          env:
            - name: WORDPRESS_DB_HOST
              value: mysql-0.mysql.blog.svc.cluster.local:3306
            - name: WORDPRESS_DB_NAME
              valueFrom:
                secretKeyRef: {name: blog-db, key: MYSQL_DATABASE}
            - name: WORDPRESS_DB_USER
              valueFrom:
                secretKeyRef: {name: blog-db, key: MYSQL_USER}
            - name: WORDPRESS_DB_PASSWORD
              valueFrom:
                secretKeyRef: {name: blog-db, key: MYSQL_PASSWORD}
          volumeMounts:
            - name: content
              mountPath: /var/www/html/wp-content
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 512Mi
          readinessProbe:
            httpGet:
              path: /wp-login.php
              port: 80
            initialDelaySeconds: 10
            periodSeconds: 10
      volumes:
        - name: content
          persistentVolumeClaim:
            claimName: wp-content
---
apiVersion: v1
kind: Service
metadata:
  name: wordpress
  namespace: blog
spec:
  selector:
    app: wordpress
  ports:
    - port: 80
      targetPort: 80

The environment variable names WORDPRESS_DB_HOST, WORDPRESS_DB_NAME, WORDPRESS_DB_USER and WORDPRESS_DB_PASSWORD belong to the official wordpress image, which writes them into wp-config.php on first start. They were tested in Docker against MySQL 8.4: the site answered with a redirect to /wp-admin/install.php and the title "WordPress > Installation", which means the database connection worked.

Why the Recreate strategy? A ReadWriteOnce volume can be mounted read-write by one node at a time. The default RollingUpdate starts the new Pod before stopping the old one, and if the scheduler puts it on another node, the new Pod is stuck in ContainerCreating with a Multi-Attach error. Recreate stops the old Pod first, at the cost of a short outage during each update (Rolling Updates, Deployment Strategies). The next model plays both strategies:

Python Updating a Pod that uses a ReadWriteOnce volume

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why one replica? WordPress keeps uploads and plugins on disk. Several replicas would each need the same files, which requires a ReadWriteMany volume (NFS, CephFS and similar) or moving uploads to object storage with a plugin. Start with one replica, and scale only after you have solved shared storage (Persistent Volumes). Sessions, caches and wp-cron are further reasons to plan before scaling.

Step 4: Ingress

YAML
# 04-ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: wordpress
  namespace: blog
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: 64m   # allow larger media uploads
spec:
  ingressClassName: nginx
  rules:
    - host: blog.example.test
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: wordpress
                port:
                  number: 80

The annotation is specific to the NGINX ingress controller; without it, uploads larger than 1 MB get a 413 error. Add a tls section and a certificate issuer for HTTPS. WordPress stores its own URL in the database (the site URL), so set it to the final https:// address in Settings > General right after installation. If you serve it on another name later, the stored URL must be changed too.

Step 5: Apply, wait and check

Terminal
kubectl apply -f 00-namespace.yaml
kubectl apply -f 01-secret.yaml            # or the create secret command above
kubectl apply -f 02-mysql.yaml
kubectl rollout status statefulset/mysql -n blog
kubectl apply -f 03-wordpress.yaml -f 04-ingress.yaml
kubectl rollout status deployment/wordpress -n blog
kubectl get pods,svc,pvc,ingress -n blog
TEXT
NAME                             READY   STATUS    RESTARTS   AGE
pod/mysql-0                      1/1     Running   0          3m
pod/wordpress-6d8f7b7c85-x2k9q   1/1     Running   0          1m

NAME                             STATUS   VOLUME     CAPACITY   STORAGECLASS
persistentvolumeclaim/data-mysql-0   Bound   pvc-...    5Gi        standard
persistentvolumeclaim/wp-content     Bound   pvc-...    2Gi        standard

(Example shape only.) Apply order matters little, because Kubernetes retries, but starting the database first makes the first WordPress start cleaner. If a PVC stays Pending, your cluster has no default StorageClass (Storage Classes); if a Pod is stuck, use the playbook in Troubleshooting.

Until DNS works, tunnel in (Debugging Applications in a Cluster):

Terminal
kubectl port-forward -n blog svc/wordpress 8080:80

Open http://localhost:8080, finish the five-minute installation (site title, admin user), and write a post with an image upload.

The model below is a reviewer's checklist for the wiring: Service selectors that match labels, Secret keys that exist, PVC names that exist, the access-mode rule and the headless DNS name. Edit the dictionaries to introduce mistakes and see the messages.

Python Check the wiring of the WordPress stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 6: Prove the data survives

Terminal
kubectl delete pod mysql-0 -n blog
kubectl delete pod -n blog -l app=wordpress
kubectl get pods -n blog -w

The StatefulSet recreates mysql-0 and re-attaches data-mysql-0; the Deployment starts a new WordPress Pod that mounts wp-content again. Reload the site: your post and its image are still there. That is the whole point of the PersistentVolumes. Note that this only proves survival of Pod restarts. It does not protect you from deleting the PVC, a bad update, or losing the storage backend.

Step 7: Back it up

  • Database: a logical dump is the simplest backup. Run it in the MySQL Pod and copy it out:
Terminal
kubectl exec -n blog mysql-0 -- sh -c \
  'mysqldump -uroot -p"$MYSQL_ROOT_PASSWORD" --single-transaction --databases wordpress' \
  > wordpress-$(date +%F).sql
  • Files: copy wp-content out (kubectl cp or a short-lived Pod that mounts the PVC and runs tar), or take a VolumeSnapshot of both PVCs if your storage supports it.
  • Schedule it with a CronJob that writes to object storage (Jobs and CronJobs), or use a tool such as Velero (Stateful Apps and Backups).
  • Test a restore into a scratch namespace. A backup you have never restored is only a hope.

Hardening and next steps

  • Add a NetworkPolicy so that only the WordPress Pods can reach MySQL port 3306 (Network Policies).
  • Run WordPress with a non-root user and a read-only root filesystem where possible (the official image runs Apache as www-data, and needs some writable paths) (Pod Security).
  • Move the database to a managed service or an operator-managed cluster for replication and point-in-time recovery.
  • Turn the five manifests into a Helm chart or Kustomize overlays, with dev and prod values (Kustomize, the Helm chart project).
  • Put the whole stack behind GitOps (GitOps).

Cleanup

Terminal
kubectl delete namespace blog

Deleting the namespace removes the Deployment, StatefulSet, Services, Secret and the wp-content claim. Whether the PersistentVolumes and their data disappear depends on the StorageClass reclaim policy (Delete removes them, Retain keeps them). Be careful: the StatefulSet's own claim data-mysql-0 is also in the namespace and is removed with it.

What is real and what is a stand-in

  • Run for this lesson: MySQL 8.4 and WordPress in Docker with the same environment variables, which reached the WordPress installation page.
  • Read-only: every Kubernetes manifest and command above. They were checked for YAML validity, not applied to a cluster.
  • Stand-ins: the two Python models.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is MySQL deployed as a StatefulSet in this project?

    A StatefulSet gives each Pod a fixed identity and per-Pod storage that stays with that identity when the Pod is rescheduled.
  2. 2. Why does the WordPress Deployment use strategy: Recreate?

    With RollingUpdate the new Pod may land on another node and get stuck on a Multi-Attach error. Recreate avoids that, with a short outage.
  3. 3. What does subPath: mysql solve?

    Some filesystems create lost+found in the root of a new volume. MySQL requires an empty data directory, so a subdirectory is used.
  4. 4. You delete the mysql-0 Pod. What happens to the database files?

    The PVC created from the volume claim template outlives Pods, and the StatefulSet re-attaches it to the Pod with the same name.
  5. 5. Which is a reliable backup for the database in this setup?

    Pod restarts are not backups. Take logical dumps or snapshots, keep them off the cluster and practice a restore.

Summary

  • Stateful apps need storage that outlives Pods: a StatefulSet with volumeClaimTemplates for MySQL, a PVC for wp-content.
  • One Secret feeds both tiers; WordPress finds the database through the headless Service name mysql-0.mysql.blog.svc.cluster.local.
  • A ReadWriteOnce volume means one replica and strategy: Recreate. Scaling WordPress needs shared storage (ReadWriteMany or object storage).
  • Use subPath for database data directories, set requests and limits, and probe MySQL with mysqladmin ping.
  • Surviving a Pod restart is not a backup: dump the database, copy or snapshot wp-content, and test the restore.

Next, install a ready-made application with Helm in Project: A Self-Hosted Git Server (Gitea) with Helm.