Registry / devops / portforward

portforward

JSON →
library0.7.6pypypi✓ verified 85d ago

The `portforward` library provides an easy-to-use Python interface for establishing port-forwarding connections to Kubernetes pods and services. It simplifies the underlying `kubernetes` client operations, allowing developers to programmatically manage forwarded ports. Currently at version 0.7.6, its release cadence is irregular, with updates typically occurring when new features or bug fixes are implemented, making it a stable choice for specific use cases.

pip install portforward
INSTALL
IMPORT
SIG · PORTFORWARD
P
portforward
devopspythonv0.7.6
Install
2.1s avg
Import
Disk
28MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.7.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 29.6MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.1s · import 0.000s · 30MB
28MB installed
● package 28MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PortForwarder
from portforward import PortForwarder
from portforward import Portforward
AsyncPortForwarder
from portforward import AsyncPortForwarder
forward
from portforward import forward

This quickstart demonstrates how to establish a port-forward to a Kubernetes pod and then make a simple HTTP request through the forwarded port. It handles common configuration loading for Kubernetes and provides error handling for typical issues. Ensure your `KUBECONFIG` is set up correctly and replace placeholder values for `namespace`, `pod_name`, `target_port`, and `local_port` with your actual Kubernetes resource details or set them via environment variables.

import os import time import requests from portforward import Portforward from kubernetes import config # --- Configuration for the quickstart example --- # Ensure you have a valid KubeConfig file (~/.kube/config) and a running Kubernetes cluster. # Replace 'nginx-pod' and 'default' with actual pod name and namespace in your cluster. # Set K8S_NAMESPACE, K8S_POD_NAME, K8S_POD_TARGET_PORT, K8S_LOCAL_PORT environment variables # or modify the defaults below to match your setup. namespace = os.environ.get("K8S_NAMESPACE", "default") pod_name = os.environ.get("K8S_POD_NAME", "nginx-pod") # Example: 'nginx-xxxxxx-xxxxx' target_port = int(os.environ.get("K8S_POD_TARGET_PORT", "80")) local_port = int(os.environ.get("K8S_LOCAL_PORT", "8080")) print(f"--- Kubernetes Port-Forward Quickstart ---") try: # Load Kubernetes configuration config.load_kube_config() print(f"Attempting to forward port {target_port} from pod '{pod_name}' in namespace '{namespace}' to local port {local_port}...") # Establish the port-forward connection using a context manager with Portforward.from_pod( namespace=namespace, pod_name=pod_name, target_port=target_port, local_port=local_port ) as pf: print(f"Successfully established port-forward: http://localhost:{pf.local_port}") print("You can now access your pod/service via this local address.") # Example: Make a request to the forwarded port print("\nAttempting a sample HTTP GET request via the forwarded port...") try: # This will only succeed if the pod exposes an HTTP service on the target_port response = requests.get(f"http://localhost:{pf.local_port}", timeout=5) print(f"Request successful! Status code: {response.status_code}") print(f"Response (first 100 chars): {response.text[:100]}...") except requests.exceptions.ConnectionError: print("Could not connect to the forwarded port. Is the target service running and exposing HTTP?") print("Please ensure the pod name, namespace, and target port are correct.") except Exception as e: print(f"An unexpected error occurred during the sample request: {e}") print("\nKeeping port-forward active for 15 seconds. Press Ctrl+C to stop sooner.") time.sleep(15) # Keep the port forward open for a duration print("Port-forward session ending.") except config.ConfigException as e: print(f"Error loading Kubernetes configuration: {e}") print("Please ensure your KubeConfig file is valid and accessible (e.g., at ~/.kube/config) or your environment is configured for in-cluster access.") except Exception as e: print(f"Failed to establish port-forward: {e}") print("Common causes: pod not found, incorrect namespace/pod_name, target_port not exposed, RBAC issues, or local port already in use.")
Debug
Known issues
gotchaKubernetes configuration issues are a common pitfall. The `portforward` library relies on the `kubernetes` client library's ability to load configuration (e.g., from `~/.kube/config`).
fix
Ensure your `kubeconfig` file is valid, accessible, and correctly pointed to (e.g., via `KUBECONFIG` environment variable or `KUBERNETES_MASTER` for direct API server access). Verify your current context is correct.
affects: All
gotchaInsufficient Kubernetes RBAC permissions can prevent port-forwarding. The user or service account needs specific permissions to 'portforward' on pods.
fix
Ensure the Kubernetes user or service account executing the Python script has `port-forward` permission on the target pod/namespace. This usually involves `verbs: ["get", "list", "watch", "create", "portforward"]` on `pods/portforward` resources.
affects: All
gotchaThe `portforward` library establishes the connection but does not validate if the specified target port inside the pod/service is actually open or serving traffic. Connecting to a non-existent internal port will result in connection issues on the local side.
fix
Double-check that the `target_port` you specify corresponds to an open port on the target pod or service that is actively listening for connections. Verify this by using `kubectl get pod <pod-name> -o yaml` to check exposed ports or `kubectl exec <pod-name> -- netstat -tuln` (if netstat is available).
affects: All
Upgrade
Version history
0.7.6latest on PyPI · released Jan 29, 2026
Audit
Dependencies
kubernetesrequiredRequired for interacting with Kubernetes clusters and performing port-forwarding operations.
requestsoptionalOften used to interact with services exposed via port-forwarding; demonstrated in quickstart.
Agent activity
2 hits · last 30 days
node
2
Resources
portforward — pip install portforward · libregistry