Skip to content

kubectl port-forward for MySQL access

kubectl port-forward for MySQL access is a networking method used to create a direct connection to a MySQL database running within a Kubernetes Pod^[400-devops__06-Kubernetes__k8s-mysql__README.md]. This technique is commonly employed by developers to interact with containerized databases using local tools for debugging or administration^[400-devops__06-Kubernetes__k8s-mysql__README.md].

Overview

The kubectl port-forward command maps a local port on the host machine to a port on the target Pod^[400-devops__06-Kubernetes__k8s-mysql__README.md]. This establishes a secure tunnel through the Kubernetes API server, allowing a client to connect to the database as if it were running locally^[400-devops__06-Kubernetes__k8s-mysql__README.md]. This approach bypasses the need to expose the database service publicly, which enhances security during development.

Usage

To establish a connection to a specific MySQL Pod instance, the standard command format requires specifying the Pod name and the ports to map^[400-devops__06-Kubernetes__k8s-mysql__README.md].

The following command forwards local port 3306 to port 3306 on the Pod mysql-dp-8dfb795cf-2hkgm:

[kubectl port-forward](<./kubectl-port-forward.md>) mysql-dp-8dfb795cf-2hkgm 3306:3306 --address 0.0.0.0

Identifying Target Pods

Before running the port-forward command, the specific name of the target Pod must be identified^[400-devops__06-Kubernetes__k8s-mysql__README.md]. This can be achieved by listing all Pods across all namespaces:

[kubectl get pods](<./kubectl-get-pods.md>) -A

Sources