---
title: "Open a tunnel"
description: "Open a TCP tunnel to an Alpacon server with an approved work session. Choose local and remote ports, run a local client, and let the CLI select a free port."
---

> Full documentation index: https://docs.alpacax.com/llms.txt

# Open a tunnel

Choose the TCP port your service uses on the server. This example connects local port 9000 to remote port 8080.

### Enable the server setting

Ask an administrator to turn on **Tunnel** for the server. See [server settings](/use/servers/manage/#tunnel-and-code-editor).

### Request a session

[Request a work session](/use/work-sessions/create/) with the target server and **Port forwarding**. Wait until the session is **Active** and note its ID.

### Sign in

```bash
alpacon login
```

Do not use `-t`: tokens cannot open a tunnel. On a machine without a browser, open the URL printed by the CLI on another device.

### Open the tunnel

```bash
alpacon tunnel --work-session WORK_SESSION_ID my-server -l 9000 -r 8080
```

Replace `WORK_SESSION_ID` with the session ID. The CLI prints `Tunnel ready: <local> -> <remote>` and `Waiting for connections... (Ctrl+C to exit)`. Connect your local client to `127.0.0.1:9000` and leave the CLI running. Press Ctrl+C when you finish.

## Run a local command with the tunnel

Put a local command after `--` to open the tunnel before starting it and close the tunnel when it exits. With an active CLI work session selected, connect a PostgreSQL client:

```bash
alpacon tunnel prod-db -l 15432 -r 5432 -- psql -h 127.0.0.1 -p 15432 -U app appdb
```

The local command is interrupted if the work session ends and closes the tunnel. See [when a tunnel ends](/use/work-sessions/tunnels/#when-a-tunnel-ends).

## Pick a free local port

Use `-l 0` to let the CLI choose a free local port:

```bash
alpacon tunnel --work-session WORK_SESSION_ID my-server -l 0 -r 8080
```

Read the selected port from `Tunnel ready: <local> -> <remote>`, then connect your client to it. The local listener binds only to `127.0.0.1`. The remote port must be from 1 to 65535.

See [`alpacon tunnel`](/reference/cli/tunnel/) for the full flag reference, and [tunnel troubleshooting](/use/work-sessions/tunnels/troubleshooting/) for errors.

Source: https://docs.alpacax.com/use/work-sessions/tunnels/open/
