Connect to an Application in Kubernetes as Localhost
This is an incredibly useful tool. If you have an application running in Kubernetes and you need to connect to you application or database, you can simply forward a port to your local machine via the
kubectl port-forward command.
Let's say you have a MySQL database running in Kubernetes and you don't want to expose it outside of your cluster, but you need to connect a client to the database to run commands against the database. Here's what you'd do...
- Determine the name of your database pod or the service that exposes it. (Preferably the master pod in a Stateful Set)
- Run the command
kubectl port-forward pods/<pod name> <local port>:<pod port>(or replace "pod" with "service")
- Connect to your application with
That's it! At this point, you should be able to connect your database client to the pod with step 3 and run the commands that you need. This same method applies to applications. Now you could browse to
http://localhost:<local port>/api/... to hit the endpoints of an HTTP REST API that you might have forwarded.