kubectl port-forward: Kubernetes Port Forwarding Guide

December 18, 2024

Introduction

The kubectl port-forward  command allows access to internal Kubernetes cluster processes from a local machine. Local access to a cluster helps debug applications and configure services in a development or testing environment without exposing them to external networks.

This tutorial shows you how to use kubectl port-forward to connect to a Kubernetes cluster resource.

kubectl port-forward: Kubernetes Port Forwarding Guide.

Prerequisites

  • Access to a Kubernetes cluster.
  • kubectl CLI tool installed.

How Does Kubernetes Port Forwarding Work?

Kubernetes provides the kubectl port-forward command for mapping local network ports to cluster resource ports. The process works as follows:

1. A user executes the kubectl port-forward command, specifying the target cluster resource (e.g., a Kubernetes pod, a replica set, or a service) and the desired port mappings.

2. The Kubernetes API server establishes an HTTP connection, creating a tunnel between the localhost and the target resource.

3. Users can now interact with the resource via the specified local port.

Why Enable Kubernetes Port Forwarding?

Port forwarding in Kubernetes simplifies development and debugging and provides secure access to internal services. Enable port forwarding when:

  • Developing and testing locally. Port forwarding allows direct interaction with applications running in a Kubernetes cluster as if running on your local machine. It simplifies the development workflow and allows users to test changes quickly without redeploying to the cluster.  
  • Debugging. Enables connecting debuggers or other tools directly to the application, making identifying and fixing issues easier.  
  • Accessing internal services. Many applications rely on backend services (e.g., databases or message queues) that are not exposed externally. Port forwarding provides a secure way to connect to these internal services from a local development environment.  
  • Troubleshooting. Port forwarding simplifies inspection, log analysis, or running diagnostic commands.
  • Needing to bypass external access restrictions. In some cases, external access to services can be restricted for security reasons. Port forwarding bypasses these restrictions for troubleshooting purposes while maintaining security.
  • Avoiding public exposure. Port forwarding creates a secure tunnel between a local machine and the cluster. Therefore, it avoids the need to expose internal services to public networks. This tunnel reduces the attack surface and improves security.
  • Accessing services without external IPs. Some services within a cluster may not have external IP addresses assigned. However, port forwarding allows access to these services without complex network configurations.  

kubectl port-forward Syntax

The port-forward command allows the user to specify the resource type and name alongside local and cluster port numbers. The basic command syntax is:

kubectl port-forward [resource-type]/[resource-name] [local-port]:[resource-port]

For example, the following code connects the resource port 80 used by a replica set named test with the local port 8080:

kubectl port-forward rs/test 8080:80

kubectl port-forward Options

kubectl port-forward has multiple options for users to customize the command according to their use case. As a result, the port-forward command has many options:

OptionDescription
--address [ip_address]Address(es) to listen on. The default value is localhost.
--as [username]Regular user or a service account to impersonate during the operation.
--as-group [group]Group to impersonate.
--as-uid [uid]UID to impersonate.
--cache-dir [path]The cache directory. The default path is $HOME/.kube/cache.
--certificate-authority [path]Path to a cert file.
--client-certificate [path]Path to a client TLS certificate.
--client-key [path]Path to a client key file for TLS.
--cluster [cluster_name]kubeconfig cluster to use.
--context [context_name]kubeconfig context to use.
--default-not-ready-toleration-seconds [integer]Toleration for notReady:NoExecute in seconds. The default value is 300.
--default-unreachable-toleration-seconds [integer]Toleration for unreachable:NoExecute in seconds. The default value is 300.
--disable-compressionDisable response compression.
-h, --helpHelp for the command.
--insecure-skip-tls-verifySkip the validity check for the server's certificate.
--kubeconfig [path]Path to the kubeconfig file for CLI requests.
--match-server-versionEnsure the client version matches the server version.
-n, --namespace [namespace]Namespace scope for the request.
--password [password]Password for API server authentication.
--pod-running-timeout [duration]Time to wait until at least one pod is running. The default value is 1m0s.
--profile [profile]Profile name. Possible values are none (default), cpu, heap, goroutine, threadcreate, block, and mutex)
--profile-output [path]File for writing the profile to.
--request-timeout [duration]Time to wait before giving up on a request. The default value is 0.
-s, --server [ip_address]:[port]Address of the Kubernetes API server.
--storage-driver-buffer-duration [duration]Buffering duration for the writes in the storage driver. The default value is 1m0s.
--storage-driver-db [database_name]Storage driver database name. The default value is cadvisor.
--storage-driver-host [host]:[port]Storage driver database address. The default value is localhost:8086.
--storage-driver-password [password]Storage driver database password. The default value is root.
--storage-driver-secureUse secure database connection.
--storage-driver-table [table_name]Storage driver database table. The default value is stats.
--storage-driver-user [database_username]Storage driver database username. The default value is root.
--tls-server-name [server_name]Server for certificate validation.
--token [token]Bearer token for API server authentication.
--user [kubeconfig_user]kubeconfig username.
--username [username]Username for API server authentication.
--version=[version]Without arguments, shows the command's version and quits. But, when followed by a version number (e.g., v1.0.0), it sets the specified version.
--warnings-as-errorsTreat server warnings as errors and exit accordingly.

How to Set Up Port Forwarding With kubectl

Setting up port forwarding with kubectl involves obtaining the resource's port data, executing the port-forward command, and connecting to the resource. Follow the steps below to complete the port forwarding procedure.

Step 1: View Available Resources

List the available resources by executing the relevant resource command. For example, to list all the services within a namespace, type the following:

kubectl -n [namespace] get svc

Then, find the service you want to forward and note its name and the port number.

Listing the services running in the default namespace of the cluster.

Step 2: Execute port-forward

Use the following command to access the resource in the cluster. For example, if the name of the service is nginx-service, and the port number is 80, expose Nginx on the local port 8080 by typing:

kubectl port-forward svc/nginx-service 8080:80

The Kubernetes API now listens to port 8080 and forwards data to the service port 80.

Port forwarding of the local port 8080 to the resource port 80.

Step 3: Connect with Resource

Use the curl command to test if the service is available at localhost:8080:

curl localhost:8080

curl prints the HTML code of the Nginx page:

The curl command showing the NGINX test page.

Also, you can visit the same address in a web browser.

A web browser window showing the NGINX test page.

Once executed, the kubectl port-forward command actively runs in the terminal window. To issue other commands while port-forwarding is running, open another terminal instance.

Note: Stop port forwarding by pressing Ctrl+C in the original terminal window.

kubectl port-forward: Common Commands

The following sections contain frequent usage scenarios for the kubectl port-forward command.

Run kubectl port-forward in Background

Start a background port-forwarding process by adding the ('&') symbol at the end of the command:

kubectl port-forward [resource_type]/[resource_name] [local_port]:[resource_port] &

Consequently, the output shows the process ID (PID) of the newly created process.

Starting a background port-forwarding process.

Press Ctrl + C after this command to use the shell prompt while the port-forwarding process runs in the background.

To stop the background process:

1. Find the PID of the port-forward process by executing this command:

ps -ef|grep port-forward
Finding the PID of the port-forwarding process.

2. Kill the process by typing:

kill -9 [PID]

The command prints no output.

Listen to Random Local Port

Use the command below to let Kubernetes choose a random local port to listen to and forward it to port 80 within the specified pod:

kubectl port-forward [resource_type]/[resource_name] :80

The port Kubernetes selected appears in the command output.

Forwarding from a random local port.

Listen on Any Local IP Address

Use the 0.0.0.0 wildcard with the --address option to listen to the local port on any local address and forward the traffic to the resource port:

kubectl port-forward --address 0.0.0.0 [resource_type]/[resource_name] [local_port]:[resource_port]
Port forwarding by listening to any local address.

Specify Local IP Address for Port Forwarding

Listen to the local port using the specified IP address and forward to the resource port by typing:

kubectl port-forward --address [local_ip_address] [resource_type]/[resource_name] [local_port]:[resource_port]
Port forwarding by listening to a specific local address.

Use Deployment to Select port-forward Port

Listen and forward data locally and within the resource using the same ports. Also, consult the deployment YAML to learn which port to use.

Execute the port-forward using the following syntax:

kubectl port-forward [resource_type]/[resource_name] [resource_port_number]:[resource_port]

For example:

kubectl port-forward deployment/nginx-deployment 8080:8080

Conclusion

After reading this tutorial, you can connect to a resource within your Kubernetes cluster using the port-forward command. Additionally, the article presented the available command options and provided an overview of the commonly used commands.

Learn more about kubectl's capabilities by reading our list of kubectl commands.

Was this article helpful?
YesNo
Vladimir Kaplarevic
Vladimir is a resident Tech Writer at phoenixNAP. He has more than 7 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His articles aim to instill a passion for innovative technologies in others by providing practical advice and using an engaging writing style.
Next you should read
Introduction to Kubernetes Persistent Volumes
January 27, 2020

Persistent Volumes are used in Kubernetes orchestration when you want to preserve the data in the volume even...
Read more
6 Kubernetes Security Best Practices: Secure Your Workloads
January 23, 2020

This article presents basic security principles such as defense-in-depth and restricted privilege...
Read more
Understanding Kubernetes Architecture with Diagrams
November 12, 2019

The article explores Kubernetes Architecture and the concept of Container Deployment. All elements of a...
Read more
How to Install a Kubernetes Cluster on CentOS 7
November 8, 2019

Use Kubernetes to launch and orchestrate your applications efficiently. The steps outlined in this tutorial...
Read more