This page shows how to use kubectl port-forward
to connect to a MongoDB server running in a Kubernetes cluster. This type of connection can be useful for database debugging.
这个页面展示了如何使用 kubectl port-forward
连接k8s集群中一个正在运行的MongoDB服务端。这种类型的连接对数据库调试很有用。
todo
Create a Deployment that runs MongoDB:
The output of a successful command verifies that the deployment was created:
View the pod status to check that it is ready:
The output displays the pod created:
View the Deployment's status:
The output displays that the Deployment was created:
The Deployment automatically manages a ReplicaSet. View the ReplicaSet status using:
The output displays that the ReplicaSet was created:
Create a Service to expose MongoDB on the network:
The output of a successful command verifies that the Service was created:
Check the Service created:
The output displays the service created:
Verify that the MongoDB server is running in the Pod, and listening on port 27017:
The output displays the port for MongoDB in that Pod:
27017 is the official TCP port for MongoDB.
kubectl port-forward
allows using resource name, such as a pod name, to select a matching pod to port forward to.
which is the same as
or
or
or
Any of the above commands works. The output is similar to this:
{{< note >}}
kubectl port-forward
does not return. To continue with the exercises, you will need to open another terminal.
{{< /note >}}
Start the MongoDB command line interface:
At the MongoDB command line prompt, enter the ping
command:
A successful ping request returns:
If you don't need a specific local port, you can let kubectl
choose and allocate
the local port and thus relieve you from having to manage local port conflicts, with
the slightly simpler syntax:
The kubectl
tool finds a local port number that is not in use (avoiding low ports numbers,
because these might be used by other applications). The output is similar to:
Connections made to local port 28015 are forwarded to port 27017 of the Pod that is running the MongoDB server. With this connection in place, you can use your local workstation to debug the database that is running in the Pod.
{{< note >}}
kubectl port-forward
is implemented for TCP ports only.
The support for UDP protocol is tracked in
issue 47862.
{{< /note >}}
Learn more about kubectl port-forward.