kubectl port-forward command

Team kubectl port-forward allows you to redirect traffic from your local computer to a specific port within the pod

Let's take a closer look.

kubectl port-forward command running

Team kubectl port-forward allows you to establish a tunnel between a local port and a resource port (pod, service, etc.) in the cluster.

General command syntax:

kubectl port-forward [resource-type]/[resource-name] [local-port]:[resource-port]
  • [resource-type]: resource type (eg pod, svc).

  • [resource-name]: resource name.

  • [local-port]: local port on your computer.

  • [resource-port]: port on the Kubernetes resource.

Examples of using:

Pod Port Forwarding

kubectl port-forward pod/my-pod 8080:80

Here we forward local port 8080 to port 80 of the pod with the name my-pod.

Service Port Forwarding

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

The example forwards local port 8080 to port 80 of a service named my-

When the team is involved kubectl port-forwardthe following happens:

  1. Initializing the command: the user enters a command in the terminal.

  2. Authentication and Authorization: The CLI contacts the Kubernetes API server to authenticate the user and check their access rights.

  3. Getting information about the pod: The CLI sends a request to get information about the target pod.

  4. Setting up a port forwarding session: The CLI initiates a connection to the API server to establish a port forwarding session.

  5. iptables configuration: The kubelet on the node running the pod configures iptables to redirect traffic.

  6. SPDY session for data transfer: Data is transferred via WebSocket/SPDY connection between the local machine and the pod.

Example of establishing a connection before data transfer

Let's say there is a pod named my-podwhich listens on port 80, and you want to forward this port to the local port 8080:

kubectl port-forward pod/my-pod 8080:80

The user enters a command kubectl port-forward pod/my-pod 8080:80. The CLI begins executing the command.

The CLI sends a request to the Kubernetes API server to authenticate the user. This request includes a Bearer Token to verify the user's identity. The API server validates the token and authorizes access to the specified pod.

After successful authentication, the CLI sends a GET request to the API server to get information about the target pod. The server returns the required data, such as the pod name, IP address, and ports.

The CLI initiates a POST request to the API server to establish a port forwarding session. The API server switches the protocol to WebSocket/SPDY, establishing a persistent connection between the local machine and the pod.

# пример кода в питоне для выполнения запроса
import requests
from requests.auth import AuthBase

class BearerAuth(AuthBase):
    def __init__(self, token):
        self.token = token

    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

url = "https://<api-server>/api/v1/namespaces/default/pods/my-pod/portforward"
token = "<token>"
headers = {"Content-Type": "application/json"}

response = requests.post(url, headers=headers, auth=BearerAuth(token))
if response.status_code == 101:  # switching Protocols
    print("Connection established")
else:
    print("Failed to establish connection", response.status_code)

The API server instructs the Kubelet on the node running the pod to configure iptables to forward traffic. The Kubelet creates iptables rules to forward traffic from local port 8080 to the pod's port 80.

Once the connection is successfully established, data is transferred via a WebSocket/SPDY connection. User requests are wrapped in WebSocket/SPDY frames and routed through the API server to the Kubelet, which then forwards them to the pod:

import websocket

def on_message(ws, message):
    print(f"Received message: {message}")

def on_error(ws, error):
    print(f"Error: {error}")

def on_close(ws):
    print("Connection closed")

def on_open(ws):
    ws.send("Hello Pod")

ws = websocket.WebSocketApp("wss://<api-server>/api/v1/namespaces/default/pods/my-pod/portforward",
                            on_message=on_message,
                            on_error=on_error,
                            on_close=on_close)
ws.on_open = on_open
ws.run_forever()

Useful options

Run in background

To run a command in the background, you can add the symbol & at the end of the command:

kubectl port-forward pod/my-pod 8080:80 &

There is a command to stop the process kill with process ID:

ps -ef | grep port-forward
kill -9 [PID]

You can let Kubernetes choose a random local port:

kubectl port-forward svc/my-service :80

The local port will be listed in the command output.

To listen on any local IP address, there is a command:

kubectl port-forward --address 0.0.0.0 pod/my-pod 8080:80

This allows you to redirect traffic from any IP address on the local machine.


Final words

kubectl port-forward – a simple and secure way to access internal cluster services. However, not everything is so rosy. There are a couple of disadvantages:

  1. No load balancing: Port forwarding works at the pod level, bypassing Kubernetes load balancing mechanisms.

  2. One-time access for one user: Only one user can establish a connection at a time.

Nevertheless,kubectl port-forward — is still a powerful tool.

You can gain more practical skills in application infrastructure within the framework of practical online courses from industry experts.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *