How to fix WordPress “Error establishing a database connection” in a Kubernetes environment

Solution 1:

You need to add targetPort in your MySQL service YAML definition. Example:


apiVersion: v1
kind: Service
metadata:
  name: db
  labels:
    name: db-service
    app: demo-wordpress-app
spec:
  ports:
    - port: 3306
      targetPort: 3306
  selector:
    name: mysql-app-label

This ensures that the service correctly forwards traffic to the MySQL container port.

Solution 2:

To fix the issue, include the targetPort in your MySQL service YAML:

targetPort: 3306

This maps the service port to the container’s MySQL port.