### Chapter: getting-started (docs/getting-started.md)

# Getting Started

This guide covers installation and your first steps with kubefwd. By the end, you'll have cluster services accessible locally by name.

## Prerequisites

- **kubectl configured** with access to a Kubernetes cluster
- **Root/sudo access** (required for `/etc/hosts` and network interface modifications)

kubefwd reads your kubeconfig (`~/.kube/config` or `KUBECONFIG` environment variable) and connects directly to the Kubernetes API. It does not invoke kubectl.

---

## Installation

=== "macOS"

    Using [Homebrew](https://brew.sh/):

    ```bash
    brew install kubefwd
    ```

    To upgrade:

    ```bash
    brew update && brew upgrade kubefwd
    ```

=== "Windows"

    Using [winget](https://learn.microsoft.com/en-us/windows/package-manager/winget/):

    ```powershell
    winget install txn2.kubefwd
    ```

    Or using [Scoop](https://scoop.sh/):

    ```powershell
    scoop install kubefwd
    ```

    To upgrade:

    ```powershell
    winget upgrade txn2.kubefwd
    # or
    scoop update kubefwd
    ```

    !!! note "Run as Administrator"
        kubefwd requires elevated privileges on Windows to modify the hosts file. Right-click your terminal and select "Run as Administrator".

=== "Linux (Debian/Ubuntu)"

    Download the `.deb` package from [GitHub Releases](https://github.com/txn2/kubefwd/releases/latest):

    ```bash
    # Install
    sudo dpkg -i kubefwd_*_amd64.deb

    # Upgrade (same command)
    sudo dpkg -i kubefwd_*_amd64.deb
    ```

=== "Linux (RHEL/Fedora)"

    Download the `.rpm` package from [GitHub Releases](https://github.com/txn2/kubefwd/releases/latest):

    ```bash
    # Install
    sudo rpm -i kubefwd_*_amd64.rpm

    # Upgrade
    sudo rpm -U kubefwd_*_amd64.rpm
    ```

=== "Linux (Manual)"

    Download and extract the tarball from [GitHub Releases](https://github.com/txn2/kubefwd/releases/latest):

    ```bash
    tar -xzf kubefwd_Linux_amd64.tar.gz
    sudo mv kubefwd /usr/local/bin/
    sudo chmod +x /usr/local/bin/kubefwd
    ```

=== "Docker"

    Run kubefwd in a privileged container:

    ```bash
    docker run -it --rm --privileged \
        -v "$HOME/.kube:/root/.kube:ro" \
        txn2/kubefwd --tui
    ```

    The container needs `--privileged` to modify network interfaces and the hosts file.

Verify installation:

```bash
kubefwd version
```

---

## Operating Modes

kubefwd supports two operating modes depending on how you want to work.

### Idle Mode (Recommended)

Start kubefwd without specifying namespaces. Add services interactively via TUI or programmatically via API.

```bash
sudo -E kubefwd --tui
```

In Idle Mode:

- **REST API** is enabled by default
- **Auto-reconnect** is enabled by default
- Use the TUI to browse namespaces, select services, and forward them
- Or use the API to add services dynamically

This is the recommended mode for interactive development. You can explore what's available in your cluster and forward exactly what you need.

### Classic Mode

Specify namespaces upfront. All services in those namespaces are forwarded immediately.

```bash
sudo -E kubefwd svc -n default --tui
```

Or without TUI for scripting:

```bash
sudo -E kubefwd svc -n default
```

Classic mode is backwards-compatible with all previous kubefwd versions. Add `--tui`, `--api`, or `-a` (auto-reconnect) as needed.

---

## Your First Forward

### Interactive (Recommended)

1. **Start kubefwd in Idle Mode:**

    ```bash
    sudo -E kubefwd --tui
    ```

2. **Browse namespaces:** Press `f` to open the service browser, then select a namespace.

3. **Forward services:** Select individual services or press `a` to forward all services in the namespace.

4. **Use your services:** They're now accessible by name:

    ```bash
    curl http://my-api:8080/health
    psql -h postgres -U admin -d mydb
    redis-cli -h redis ping
    ```

5. **Quit:** Press `q` to exit. kubefwd cleans up automatically.

### Quick Start (Classic Mode)

Forward all services in a namespace immediately:

```bash
sudo -E kubefwd svc -n my-namespace --tui
```

You'll see the TUI with all services from `my-namespace` being forwarded.

---

## What Happens Under the Hood

When kubefwd forwards a service:

1. **IP Allocation**: Each service gets a unique loopback IP (e.g., `127.1.27.1`, `127.1.27.2`)

2. **Hosts File Update**: Service names are added to `/etc/hosts`:
   ```
   127.1.27.1    my-api
   127.1.27.2    postgres
   127.1.27.3    redis
   ```

3. **Port Forwarding**: kubefwd creates port forwards to pods backing each service

4. **Ready to Use**: Your applications can connect using service names, exactly like in-cluster

```
Your App → postgres:5432
         ↓
/etc/hosts: postgres = 127.1.27.2
         ↓
kubefwd listening on 127.1.27.2:5432
         ↓
Kubernetes API → Pod in cluster
```

### Unique IPs Solve Port Conflicts

Unlike `kubectl port-forward` which binds to a single port, kubefwd assigns each service its own IP address. This means:

- Multiple databases on port 5432? No problem.
- Multiple web services on port 80? Works fine.
- Every service uses its real port, just like in-cluster.

### Cleanup

When kubefwd exits (via `q` or `Ctrl+C`):

- `/etc/hosts` entries are removed
- Network interface aliases are cleaned up
- All port forward connections are closed

Your original hosts file is backed up to `~/hosts.original` for safety.

---

## Why sudo -E?

kubefwd requires root privileges for:

- Modifying `/etc/hosts`
- Creating loopback IP aliases on the network interface
- Binding to ports below 1024

The `-E` flag preserves your environment variables, especially `KUBECONFIG`:

```bash
# Correct - preserves KUBECONFIG
sudo -E kubefwd --tui

# Wrong - may fail to find cluster config
sudo kubefwd --tui
```

---

## Enabling the REST API

The REST API allows programmatic control of kubefwd and enables AI assistant integration via MCP.

**Idle Mode** (API enabled by default):
```bash
sudo -E kubefwd
sudo -E kubefwd --tui
```

**Classic Mode** (add `--api` flag):
```bash
sudo -E kubefwd svc -n default --api
```

The API is available at:

- `http://kubefwd.internal/api` - REST endpoints
- `http://kubefwd.internal/docs` - Interactive API documentation

See [REST API Reference](api-reference.md) for endpoints and [MCP Integration](mcp-integration.md) for AI assistant setup.

---

## Common Commands

```bash
# Idle mode with TUI (recommended for interactive use)
sudo -E kubefwd --tui

# Forward specific namespace with TUI
sudo -E kubefwd svc -n my-namespace --tui

# Forward multiple namespaces
sudo -E kubefwd svc -n frontend,backend,data --tui

# Forward with label selector
sudo -E kubefwd svc -n default -l app=myapp --tui

# Classic mode (no TUI, for scripts)
sudo -E kubefwd svc -n default

# Enable verbose logging
sudo -E kubefwd svc -n default -v
```

---

## Next Steps

- **[User Guide](user-guide.md)** - Master the interactive interface
- **[Configuration](configuration.md)** - All command-line options
- **[Advanced Usage](advanced-usage.md)** - Multi-namespace, selectors, port mapping
- **[MCP Integration](mcp-integration.md)** - AI assistant setup

### Chapter: index (docs/index.md)

---
title: kubefwd
description: Bulk port forward Kubernetes services to unique loopback IPs with /etc/hosts integration. Interactive TUI, REST API, and MCP server for AI assistants.
template: home.html
hide:
  - navigation
  - toc
  - footer
---

### Chapter: api-reference (docs/api-reference.md)

# REST API

kubefwd's REST API enables programmatic control over port forwarding. Build custom tooling, integrate with CI/CD pipelines, or create dashboards that dynamically manage which services are forwarded. Add and remove namespaces or individual services on the fly, query real-time metrics, stream events via SSE, and diagnose connection issues without restarting kubefwd.

## Quick Start

```bash
# Idle mode - API enabled by default, add namespaces dynamically
sudo -E kubefwd

# Or forward a namespace with API enabled
sudo -E kubefwd svc -n default --api

# Test the API
curl http://kubefwd.internal/api/health
```

The API is available at `http://kubefwd.internal/api`. 

Interactive documentation is at `http://kubefwd.internal/docs`.



## Overview

| Property | Value |
|----------|-------|
| Base URL | `http://kubefwd.internal/api` |
| Authentication | Bearer token (all endpoints except `/api/health`) |
| Response Format | JSON |
| OpenAPI Spec | `/openapi.yaml` |

All responses use this wrapper format:

```json
{
  "success": true,
  "data": { ... },
  "error": null
}
```

Error responses:

```json
{
  "success": false,
  "data": null,
  "error": {
    "code": "NOT_FOUND",
    "message": "Service not found"
  }
}
```

---

## Authentication

Every endpoint **except `/api/health`** requires a Bearer token. Send it in the
`Authorization` header:

```bash
curl http://kubefwd.internal/api/services \
  -H "Authorization: Bearer $KUBEFWD_API_KEY"
```

Requests with a missing or invalid key get `401 Unauthorized`:

```json
{
  "success": false,
  "data": null,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "API key required. Pass via Authorization: Bearer <key>"
  }
}
```

### Getting the key

kubefwd resolves the key at startup from the `KUBEFWD_API_KEY` environment
variable. If that variable is unset, it generates a random 32-character hex key
and prints the **full key** to the console when the server starts (this is the
only way to learn a generated key):

```
API key (generated): 8f3c2a1b9d4e6f70a1b2c3d4e5f60718
Set KUBEFWD_API_KEY to pin your own key instead.
```

To pin a known key — recommended for automation, CI, or the [MCP bridge](mcp-integration.md) —
set the variable before launching:

```bash
export KUBEFWD_API_KEY=my-known-key
sudo -E kubefwd --api
```

When you supply the key this way, kubefwd does **not** echo it to the console —
it only logs that the key was read from `KUBEFWD_API_KEY`, since you already
know its value:

```
API key: using KUBEFWD_API_KEY from environment
```

> The API binds to a loopback address (127.2.27.1) and is only reachable from
> localhost, but the token is still required: any local process could otherwise
> drive kubefwd against your kubeconfig (it runs as root via `sudo -E`).

> **Note:** The `curl` examples below omit the `Authorization` header for
> readability. Add `-H "Authorization: Bearer $KUBEFWD_API_KEY"` to every
> request except `/api/health`.

---

## Health & Info

### GET /api/health

Health check endpoint.

```bash
curl http://kubefwd.internal/api/health
```

```json
{
  "status": "healthy",
  "timestamp": "2025-01-15T10:30:00Z"
}
```

### GET /api/info

Server information and version.

```bash
curl http://kubefwd.internal/api/info
```

```json
{
  "version": "1.26.0",
  "uptime": "2h15m30s",
  "startedAt": "2025-01-15T08:15:00Z"
}
```

---

## Services

### GET /api/v1/services

List all forwarded services.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| namespace | string | Filter by namespace |
| context | string | Filter by context |
| status | string | Filter by status (active, error) |

```bash
# List all services
curl http://kubefwd.internal/api/v1/services

# Filter by namespace
curl http://kubefwd.internal/api/v1/services?namespace=default
```

### GET /api/v1/services/:key

Get a specific service. Key format: `service-name.namespace.context`

```bash
curl http://kubefwd.internal/api/v1/services/api-gateway.default.minikube
```

### POST /api/v1/services

Add a new service to forward.

```bash
curl -X POST http://kubefwd.internal/api/v1/services \
  -H "Content-Type: application/json" \
  -d '{
    "namespace": "default",
    "service_name": "my-service",
    "context": "minikube"
  }'
```

### DELETE /api/v1/services/:key

Stop forwarding a service.

```bash
curl -X DELETE http://kubefwd.internal/api/v1/services/my-service.default.minikube
```

### POST /api/v1/services/:key/reconnect

Reconnect a specific service.

```bash
curl -X POST http://kubefwd.internal/api/v1/services/api-gateway.default.minikube/reconnect
```

### POST /api/v1/services/:key/sync

Sync service with Kubernetes (refresh pods).

```bash
curl -X POST http://kubefwd.internal/api/v1/services/api-gateway.default.minikube/sync
```

### POST /api/v1/services/reconnect

Reconnect all services (or all errored services).

```bash
# Reconnect all errored services
curl -X POST http://kubefwd.internal/api/v1/services/reconnect

# Force reconnect all services
curl -X POST "http://kubefwd.internal/api/v1/services/reconnect?force=true"
```

---

## Forwards

Individual port forwards (a service may have multiple forwards for different pods/ports).

### GET /api/v1/forwards

List all active port forwards.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| namespace | string | Filter by namespace |
| service | string | Filter by service name |
| status | string | Filter by status |

```bash
curl http://kubefwd.internal/api/v1/forwards
```

### GET /api/v1/forwards/:key

Get details for a specific forward.

```bash
curl http://kubefwd.internal/api/v1/forwards/api-gateway-pod-abc.default.minikube
```

### GET /api/v1/forwards/:key/http

Get HTTP traffic captured for a forward.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| count | integer | Number of entries (default: 50) |

```bash
curl http://kubefwd.internal/api/v1/forwards/api-gateway.default.minikube/http?count=10
```

---

## Namespaces

Manage namespace watchers dynamically.

### GET /api/v1/namespaces

List active namespace watchers.

```bash
curl http://kubefwd.internal/api/v1/namespaces
```

### GET /api/v1/namespaces/:key

Get details for a namespace watcher. Key format: `namespace.context`

```bash
curl http://kubefwd.internal/api/v1/namespaces/default.minikube
```

### POST /api/v1/namespaces

Add a namespace watcher (start forwarding all services in namespace).

```bash
curl -X POST http://kubefwd.internal/api/v1/namespaces \
  -H "Content-Type: application/json" \
  -d '{
    "namespace": "staging",
    "context": "minikube"
  }'
```

### DELETE /api/v1/namespaces/:key

Remove a namespace watcher (stop forwarding all services in namespace).

```bash
curl -X DELETE http://kubefwd.internal/api/v1/namespaces/staging.minikube
```

---

## Kubernetes Discovery

Query the Kubernetes cluster for available resources.

### GET /api/v1/kubernetes/contexts

List available kubeconfig contexts.

```bash
curl http://kubefwd.internal/api/v1/kubernetes/contexts
```

### GET /api/v1/kubernetes/namespaces

List namespaces in a context.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| context | string | Kubernetes context (uses current if omitted) |

```bash
curl http://kubefwd.internal/api/v1/kubernetes/namespaces?context=minikube
```

### GET /api/v1/kubernetes/services

List services in a namespace.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| namespace | string | Namespace (required) |
| context | string | Kubernetes context |

```bash
curl "http://kubefwd.internal/api/v1/kubernetes/services?namespace=default&context=minikube"
```

### GET /api/v1/kubernetes/services/:namespace/:name

Get details for a specific Kubernetes service.

```bash
curl http://kubefwd.internal/api/v1/kubernetes/services/default/api-gateway
```

### GET /api/v1/kubernetes/pods/:namespace

List pods in a namespace with status, ready state, restarts, and age.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| context | string | Kubernetes context (uses current if omitted) |
| labelSelector | string | Filter pods by labels (e.g., "app=nginx") |
| serviceName | string | Filter to pods backing this service |

```bash
# List all pods in namespace
curl http://kubefwd.internal/api/v1/kubernetes/pods/default

# Filter by label
curl "http://kubefwd.internal/api/v1/kubernetes/pods/default?labelSelector=app=nginx"

# Filter by service
curl "http://kubefwd.internal/api/v1/kubernetes/pods/default?serviceName=api-gateway"
```

### GET /api/v1/kubernetes/pods/:namespace/:podName

Get detailed pod information including containers, status, conditions, and resources.

```bash
curl http://kubefwd.internal/api/v1/kubernetes/pods/default/api-gateway-7d4f5b6c8-abc12
```

### GET /api/v1/kubernetes/pods/:namespace/:podName/logs

Get logs from a pod's container.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| context | string | Kubernetes context (uses current if omitted) |
| container | string | Container name (defaults to first container) |
| tailLines | integer | Lines from end (default: 100, max: 1000) |
| sinceTime | string | RFC3339 timestamp to start from |
| previous | boolean | Get logs from previous container instance |
| timestamps | boolean | Include timestamps in output |

```bash
# Get last 100 lines
curl http://kubefwd.internal/api/v1/kubernetes/pods/default/api-gateway-7d4f5b6c8-abc12/logs

# Get last 50 lines with timestamps
curl "http://kubefwd.internal/api/v1/kubernetes/pods/default/api-gateway-7d4f5b6c8-abc12/logs?tailLines=50&timestamps=true"

# Get logs from specific container
curl "http://kubefwd.internal/api/v1/kubernetes/pods/default/api-gateway-7d4f5b6c8-abc12/logs?container=sidecar"
```

### GET /api/v1/kubernetes/events/:namespace

Get Kubernetes events for debugging. Shows scheduling, pulling, starting, and killing events.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| context | string | Kubernetes context (uses current if omitted) |
| resourceKind | string | Filter by kind (Pod, Service, Deployment) |
| resourceName | string | Filter by resource name |
| limit | integer | Max events to return (default: 50) |

```bash
# Get all events in namespace
curl http://kubefwd.internal/api/v1/kubernetes/events/default

# Filter to pod events
curl "http://kubefwd.internal/api/v1/kubernetes/events/default?resourceKind=Pod"

# Get events for specific pod
curl "http://kubefwd.internal/api/v1/kubernetes/events/default?resourceKind=Pod&resourceName=api-gateway-7d4f5b6c8-abc12"
```

### GET /api/v1/kubernetes/endpoints/:namespace/:serviceName

Get endpoints for a service. Shows which pods are backing the service and their ready state.

```bash
curl http://kubefwd.internal/api/v1/kubernetes/endpoints/default/api-gateway
```

---

## Metrics

Traffic and performance metrics.

### GET /api/v1/metrics

Summary metrics for all forwards.

```bash
curl http://kubefwd.internal/api/v1/metrics
```

```json
{
  "totalServices": 15,
  "activeForwards": 23,
  "totalBytesIn": 1048576,
  "totalBytesOut": 524288,
  "uptime": "2h15m"
}
```

### GET /api/v1/metrics/services

Metrics grouped by service.

```bash
curl http://kubefwd.internal/api/v1/metrics/services
```

### GET /api/v1/metrics/services/:key

Detailed metrics for a specific service.

```bash
curl http://kubefwd.internal/api/v1/metrics/services/api-gateway.default.minikube
```

### GET /api/v1/metrics/services/:key/history

Historical metrics for a service (time series data).

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| duration | string | Time window (e.g., "1h", "30m") |
| interval | string | Bucket interval (e.g., "1m", "5m") |

```bash
curl "http://kubefwd.internal/api/v1/metrics/services/api-gateway.default.minikube/history?duration=1h"
```

---

## Diagnostics

Error analysis and troubleshooting.

### GET /api/v1/diagnostics

Diagnostics summary.

```bash
curl http://kubefwd.internal/api/v1/diagnostics
```

### GET /api/v1/diagnostics/errors

List current errors.

```bash
curl http://kubefwd.internal/api/v1/diagnostics/errors
```

### GET /api/v1/diagnostics/services/:key

Diagnostics for a specific service.

```bash
curl http://kubefwd.internal/api/v1/diagnostics/services/api-gateway.default.minikube
```

### GET /api/v1/diagnostics/forwards/:key

Diagnostics for a specific forward.

```bash
curl http://kubefwd.internal/api/v1/diagnostics/forwards/api-gateway.default.minikube
```

### GET /api/v1/diagnostics/network

Network interface diagnostics.

```bash
curl http://kubefwd.internal/api/v1/diagnostics/network
```

---

## Analysis

AI-friendly status and analysis endpoints.

### GET /api/v1/status

Quick status overview optimized for AI tools.

```bash
curl http://kubefwd.internal/api/v1/status
```

```json
{
  "status": "healthy",
  "message": "All services forwarding normally",
  "totalServices": 15,
  "activeServices": 15,
  "errorCount": 0
}
```

### GET /api/v1/analyze

Detailed analysis with recommendations.

```bash
curl http://kubefwd.internal/api/v1/analyze
```

---

## History

Event and error history.

### GET /api/v1/history/events

Recent events.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| count | integer | Number of events (default: 50) |

```bash
curl http://kubefwd.internal/api/v1/history/events?count=20
```

### GET /api/v1/history/errors

Error history.

```bash
curl http://kubefwd.internal/api/v1/history/errors?count=20
```

### GET /api/v1/history/reconnections

All reconnection events.

```bash
curl http://kubefwd.internal/api/v1/history/reconnections
```

### GET /api/v1/services/:key/history/reconnections

Reconnection history for a specific service.

```bash
curl http://kubefwd.internal/api/v1/services/api-gateway.default.minikube/history/reconnections
```

### GET /api/v1/history/stats

Aggregated history statistics.

```bash
curl http://kubefwd.internal/api/v1/history/stats
```

---

## Logs

Application logs.

### GET /api/v1/logs

Recent log entries.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| count | integer | Number of entries (default: 100) |
| level | string | Filter by level (debug, info, warn, error) |
| service | string | Filter by service |

```bash
curl "http://kubefwd.internal/api/v1/logs?count=50&level=error"
```

### GET /api/v1/logs/stream

Server-Sent Events (SSE) stream of logs.

```bash
curl http://kubefwd.internal/api/v1/logs/stream
```

### GET /api/v1/logs/system

System-level logs.

```bash
curl http://kubefwd.internal/api/v1/logs/system
```

### DELETE /api/v1/logs/system

Clear system logs.

```bash
curl -X DELETE http://kubefwd.internal/api/v1/logs/system
```

---

## Events (SSE)

### GET /api/v1/events

Server-Sent Events stream for real-time updates.

```bash
curl http://kubefwd.internal/api/v1/events
```

Event types:

- `service.added` - New service started forwarding
- `service.removed` - Service stopped forwarding
- `service.error` - Service encountered an error
- `forward.connected` - Port forward established
- `forward.disconnected` - Port forward lost
- `pod.added` - Pod added to service
- `pod.removed` - Pod removed from service

Example event:

```
event: service.added
data: {"key":"api-gateway.default.minikube","namespace":"default","service":"api-gateway"}
```

---

## HTTP Traffic

HTTP request/response capture for debugging.

### GET /api/v1/services/:key/http

HTTP traffic for a service.

**Query Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| count | integer | Number of entries (default: 50) |

```bash
curl http://kubefwd.internal/api/v1/services/api-gateway.default.minikube/http?count=10
```

---

## Error Codes

| Code | Description |
|------|-------------|
| `NOT_FOUND` | Resource not found |
| `BAD_REQUEST` | Invalid request parameters |
| `INTERNAL_ERROR` | Server error |
| `ALREADY_EXISTS` | Resource already exists |
| `CONFLICT` | Operation conflicts with current state |

---

## See Also

- [Getting Started](getting-started.md) - Installation and basic usage
- [MCP Integration](mcp-integration.md) - AI assistant integration
- [Configuration](configuration.md) - CLI flags reference