> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Telepresence Intercept

> Guide to use Telepresence to intercept Kubernetes service traffic so you can run and debug a service locally while the cluster routes requests to your workstation.

This guide shows how to use Telepresence to intercept traffic for a Kubernetes deployment so you can run and debug a service locally while cluster traffic is routed to your workstation. This is ideal for faster iteration: no image build/push cycles are required and you can use your IDE and debugger directly.

Prerequisite: Telepresence is already connected to the cluster (verify with `telepresence status`).

## 1) Find the deployment to intercept

List deployments to identify the workload you want to intercept (example: `auth-depl`):

```bash theme={null}
kubectl get deployment
```

Example output:

```text theme={null}
NAME                READY   UP-TO-DATE   AVAILABLE   AGE
auth-depl           1/1     1            1           4h55m
inventory-depl      1/1     1            1           5h32m
products-depl       1/1     1            1           4h47m
```

You can also confirm Telepresence connectivity before creating an intercept:

```bash theme={null}
telepresence status
# shows connection status and current intercepts
```

## 2) Choose local and service ports

Decide which local port your process will listen on and the service port used by the pod.

| Role | Example |
| - | - |
| Local port on your machine (destination for forwarded traffic) | `8000` |
| Service/Pod port (the port the app expects inside the cluster) | `3000` |

If the pod only exposes one port, the service port suffix can be omitted in the intercept command. If multiple ports exist on the workload, specify the service port (e.g., `:3000`).

## 3) Create the intercept

Map a local port to the service port and create the intercept:

```bash theme={null}
telepresence intercept auth-depl -p 8000:3000
```

Example Telepresence confirmation:

```text theme={null}
Using Deployment auth-depl
    Intercept name        : auth-depl
    State                 : ACTIVE
    Workload kind         : Deployment
    Destination           : 127.0.0.1:8000
    Service Port Identifier: 3000/TCP
    Volume Mount Point    : /tmp/telfs-1680244885
    Intercepting          : all TCP connections
```

When active, Telepresence injects the traffic agent into the pod and forwards service traffic to `127.0.0.1:8000` on your machine.

## 4) Run the service locally

Switch to the service directory and start the app so it listens on the chosen local port (`8000` in the example).

Example `index.js` (auth service) listening on port 8000:

```javascript theme={null}
// index.js
const express = require("express");
const app = express();
const port = 8000;

app.get("/", (req, res) => {
  res.json({ message: "this is the auth service running on my machine" });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
```

Start the service locally (example uses nodemon):

```bash theme={null}
npm run dev
```

Example output:

```text theme={null}
> auth@1.0.0 dev
> nodemon index.js

[nodemon] 3.1.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] starting `node index.js`
Example app listening on port 8000
```

<Callout icon="lightbulb" color="#1CB2FE">
  Running the service locally lets you use your IDE and debugger directly on code that would otherwise run in the cluster — no image build/push required.
</Callout>

## 5) Verify the cluster routes traffic to your local process

From inside the cluster (for example, from another pod or using cluster DNS), a request to the service name should route to your local process.

Example: curl the service `auth-service` on port `3000` from another pod:

```bash theme={null}
curl http://auth-service:3000
```

Expected response:

```json theme={null}
{"message":"this is the auth service running on my machine"}
```

This demonstrates that Telepresence forwarded cluster traffic to your workstation.

## 6) What Telepresence installs in the pod?

When an intercept is active, Telepresence adds a `traffic-agent` container to the intercepted pod to forward traffic.

Inspect pods and describe the intercepted pod:

```bash theme={null}
kubectl get pod
kubectl describe pod <auth-pod-name>
```

Example excerpt (condensed):

```text theme={null}
Containers:
  auth:
    Port: 3000/TCP
    State: Running
    Ready: True
  traffic-agent:
    Image: ghcr.io/telepresenceio/tel2:2.20.0
    Port: 9900/TCP
    State: Running
    Ready: True
```

The `traffic-agent` container is responsible for redirecting the pod traffic to your machine.

## 7) Remove an intercept

List current intercepts:

```bash theme={null}
telepresence list
```

Example output while `auth-depl` is intercepted:

```text theme={null}
auth-depl : intercepted
    Intercept name    : auth-depl
    State             : ACTIVE
    Workload kind     : Deployment
    Destination       : 127.0.0.1:8000
    Service Port Identifier : 3000/TCP
    Volume Mount Point : /tmp/telfs-1680244885
```

To remove the intercept:

```bash theme={null}
telepresence leave auth-depl
```

Verify it has been removed:

```bash theme={null}
telepresence list
```

Example output after leaving:

```text theme={null}
auth-depl : ready to intercept (traffic-agent already installed)
inventory-depl    : ready to intercept (traffic-agent not yet installed)
products-depl     : ready to intercept (traffic-agent not yet installed)
```

## 8) Intercept another service (example: products)

Repeat the same workflow for additional deployments. Example for `products-depl`:

1. Identify the deployment:

```bash theme={null}
kubectl get deployment
```

2. Create an intercept (use a different local port if `8000` is in use, e.g., `9000`):

```bash theme={null}
telepresence intercept products-depl -p 8000:3000
```

3. Run the `products` service locally and ensure it listens on the chosen port.

Note: Multiple intercepts can be active simultaneously; ensure local ports do not conflict.

## 9) Debugging: missing environment variables when running locally

When you run service code outside the pod, the pod's environment variables are not automatically available on your machine. If the service relies on pod-provided env vars (for service discovery, API URLs, credentials, etc.), you must replicate them locally.

Example symptom observed for the `products` service:

* Public LoadBalancer requests hung.
* Local `products` process logged:

```text theme={null}
TypeError: Failed to parse URL from undefined?product_ids=1,2,3
    at new URL (node:internal/url:816:29)
    ...
```

This indicates `API_URL` was undefined locally. Relevant server code:

```javascript theme={null}
app.get("/", async (req, res) => {
  try {
    const productIds = req.query.product_ids;
    console.log(productIds);
    const idsArray = productIds.split(",").map((id) => parseInt(id.trim(), 10));
    console.log(idsArray);
    const filteredProducts = products.filter((product) =>
      idsArray.includes(product.id)
    );
    console.log(filteredProducts);

    const response = await fetch(`${apiURL}?product_ids=${idsArray.join(",")}`);
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const { data } = await response.json();
    // ...
  } catch (err) {
    console.error(err);
    res.status(500).send("Internal Server Error");
  }
});
```

`apiURL` was populated from an environment variable:

```javascript theme={null}
require('dotenv').config({ override: true });
const apiURL = process.env.API_URL;
console.log("API_URL:", process.env.API_URL);
```

In the deployment manifest the pod receives `API_URL`:

```yaml theme={null}
env:
  - name: "API_URL"
    value: "http://inventory-service:3000/"
```

To avoid runtime errors when developing locally, provide the same env vars on your workstation. Options:

* Create a `.env` file and use `dotenv`.
* `export API_URL="http://inventory-service:3000/"` in your shell.
* Use a tooling approach to inject pod env into your local environment.

<Callout icon="lightbulb" color="#1CB2FE">
  Tip: If you see a URL- or host-related error after intercepting, check that any service discovery or env vars used to contact other services are present in your local environment.
</Callout>

## Summary & quick reference

* Create an intercept:
  * `telepresence intercept <deployment> -p <localPort>:<servicePort>`
* Start your service locally on `<localPort>`.
* Telepresence injects a `traffic-agent` container into the pod to forward traffic.
* To remove an intercept: `telepresence leave <intercept-name>`.
* Remember to replicate pod environment variables locally if your code depends on them.

## Links and references

* Telepresence documentation: [https://www.telepresence.io/docs/](https://www.telepresence.io/docs/)
* Kubernetes docs (Deployments): [https://kubernetes.io/docs/concepts/workloads/controllers/deployment/](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/)
* Node.js: [https://nodejs.org/](https://nodejs.org/)
* Express: [https://expressjs.com/](https://expressjs.com/)

You can fetch and replicate a pod's environment variables locally so your process behaves identically to the pod.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/telepresence-for-kubernetes/module/0eb5dcb6-2e2a-40d9-9caa-bd3149741aeb/lesson/93238627-79c8-49f3-b86d-cdff5e1a91b9" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.