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

# Connect a sandbox to a VPN with OpenVPN

> Install OpenVPN in a sandbox, upload a .ovpn client profile, start the tunnel in the background, and confirm that the tun0 interface is up.

A sandbox can join an OpenVPN network through a `.ovpn` client configuration file, so it reaches private networks through the VPN tunnel. This is useful for accessing internal services, using a fixed egress path, or routing selected traffic through your own infrastructure.

> [!NOTE]
>
> Install the SDK, or the CLI for `ppio` commands, and set the `PPIO_API_KEY` and `PPIO_DOMAIN` environment variables before running these examples. See [Quickstart](https://docs.ppio.ai/sandbox/quickstart.md) and [Install and authenticate](https://docs.ppio.ai/sandbox/cli/install.md).

> [!NOTE]
>
> An OpenVPN server and a `.ovpn` client profile for it are required. This page uploads the profile into the sandbox and starts the client inside it.

## Connection path

The flow is: create a sandbox, install OpenVPN, upload the `.ovpn` config, start OpenVPN in the background, then verify that the `tun0` tunnel interface is up.

```mermaid theme={null}
flowchart LR
  SDK[SDK] -->|"control channel, default route"| S[Sandbox]
  S -->|tun0| V[OpenVPN server]
  V --> P[Private network]
```

## Connect a sandbox to OpenVPN

The program reads the profile `client1.ovpn` from the parent directory of the script, writes it to `/tmp/client.ovpn` inside the sandbox, starts the client with `background=True`, and checks the tunnel.

**client1.ovpn**

**script directory**

**ppio-openvpn.py**

**index.mts**

**1. Create the sandbox**

```python Python theme={null}
    # Create the sandbox
    print("Creating sandbox...")
    sandbox = ppio.sandbox.create("base")
    print(f"Sandbox created: {sandbox.sandbox_id}")
```

```javascript Node.js theme={null}
  // Create the sandbox
  console.log('Creating sandbox...')
  const sandbox = await ppio.sandbox.create('base')
  console.log(`Sandbox created: ${sandbox.sandboxId}`)
```

**2. Install OpenVPN**

```python Python theme={null}
    # Step 1: Install OpenVPN
    print("\nInstalling OpenVPN...")
    response = sandbox.commands.run(
        "sudo apt update && sudo apt install -y openvpn",
        timeout=300,
    )
    if response.exit_code != 0:
        print(f"Error installing OpenVPN: {response.stderr}")
        return sandbox
    print("OpenVPN installed successfully.")
```

```javascript Node.js theme={null}
  // Step 1: Install OpenVPN
  console.log('\nInstalling OpenVPN...')
  const install = await sandbox.commands.run(
    'sudo apt update && sudo apt install -y openvpn',
    { timeoutMs: 300_000 }
  )
  if (install.exitCode !== 0) {
    console.log(`Error installing OpenVPN: ${install.stderr}`)
    return sandbox
  }
  console.log('OpenVPN installed successfully.')
```

**3. Write the config file**

```python Python theme={null}
    # Step 2: Write the OpenVPN config file
    print("\nWriting OpenVPN configuration...")
    sandbox.files.write(REMOTE_CONFIG, ovpn_config)
    print(f"Configuration written to {REMOTE_CONFIG}")
```

```javascript Node.js theme={null}
  // Step 2: Write the OpenVPN config file
  console.log('\nWriting OpenVPN configuration...')
  await sandbox.files.write(REMOTE_CONFIG, ovpnConfig)
  console.log(`Configuration written to ${REMOTE_CONFIG}`)
```

**4. Start OpenVPN in the background**

```python Python theme={null}
    # Step 3: Start OpenVPN in background.
    #   `--pull-filter ignore redirect-gateway` stops the server from taking
    #   over the sandbox default route, otherwise the SDK control connection
    #   gets pulled into the tunnel and every later command times out. The VPN
    #   subnet routes are still installed.
    print("\nStarting OpenVPN tunnel...")
    sandbox.commands.run(
        f'nohup sudo openvpn --config {REMOTE_CONFIG} '
        f'--pull-filter ignore "redirect-gateway" '
        f"> {REMOTE_LOG} 2>&1 &",
        background=True,
    )

    # Wait for connection to establish
    print("Waiting for VPN connection to establish...")
    time.sleep(10)
```

```javascript Node.js theme={null}
  // Step 3: Start OpenVPN in background.
  //   `--pull-filter ignore redirect-gateway` stops the server from taking
  //   over the sandbox default route, otherwise the SDK control connection
  //   gets pulled into the tunnel and every later command times out. The VPN
  //   subnet routes are still installed.
  console.log('\nStarting OpenVPN tunnel...')
  await sandbox.commands.run(
    `nohup sudo openvpn --config ${REMOTE_CONFIG} ` +
      `--pull-filter ignore "redirect-gateway" ` +
      `> ${REMOTE_LOG} 2>&1 &`,
    { background: true }
  )

  // Wait for connection to establish
  console.log('Waiting for VPN connection to establish...')
  await new Promise((r) => setTimeout(r, 10_000))
```

**5. Verify the tun0 interface**

```python Python theme={null}
    # Step 4: Verify connection - check if the tun0 interface exists
    print("\nVerifying OpenVPN connection...")
    response = sandbox.commands.run("ip addr show tun0 2>/dev/null || true")
    if "inet " in response.stdout:
        print("VPN tunnel interface (tun0) is up:")
        print(response.stdout)
    else:
        print("Warning: tun0 interface not found. Checking OpenVPN logs...")
        log = sandbox.commands.run(f"cat {REMOTE_LOG} 2>/dev/null || true")
        print(f"OpenVPN log:\n{log.stdout}")
        return sandbox
```

```javascript Node.js theme={null}
  // Step 4: Verify connection - check if the tun0 interface exists
  console.log('\nVerifying OpenVPN connection...')
  const res = await sandbox.commands.run('ip addr show tun0 2>/dev/null || true')
  if (res.stdout.includes('inet ')) {
    console.log('VPN tunnel interface (tun0) is up:')
    console.log(res.stdout)
  } else {
    console.log('Warning: tun0 interface not found. Checking OpenVPN logs...')
    const log = await sandbox.commands.run(`cat ${REMOTE_LOG} 2>/dev/null || true`)
    console.log(`OpenVPN log:\n${log.stdout}`)
    return sandbox
  }
```

If it does not come up, inspect `/tmp/openvpn.log`.

### Full example

```python Python theme={null}
"""ppio-openvpn.py

Connect a sandbox to an OpenVPN network using a `.ovpn` client
configuration file (non-interactive).
"""

import os
import time

from ppio_sandbox import PPIO

# Path to the local .ovpn client profile, one directory above the script.
OVPN_PATH = os.path.join(os.path.dirname(__file__), "..", "client1.ovpn")
REMOTE_CONFIG = "/tmp/client.ovpn"
REMOTE_LOG = "/tmp/openvpn.log"


def setup_openvpn(ovpn_config: str):
    """Connect a sandbox to an OpenVPN network."""
    ppio = PPIO(api_key=os.environ["PPIO_API_KEY"])

    # Create the sandbox
    print("Creating sandbox...")
    sandbox = ppio.sandbox.create("base")
    print(f"Sandbox created: {sandbox.sandbox_id}")

    # Step 1: Install OpenVPN
    print("\nInstalling OpenVPN...")
    response = sandbox.commands.run(
        "sudo apt update && sudo apt install -y openvpn",
        timeout=300,
    )
    if response.exit_code != 0:
        print(f"Error installing OpenVPN: {response.stderr}")
        return sandbox
    print("OpenVPN installed successfully.")

    # Step 2: Write the OpenVPN config file
    print("\nWriting OpenVPN configuration...")
    sandbox.files.write(REMOTE_CONFIG, ovpn_config)
    print(f"Configuration written to {REMOTE_CONFIG}")

    # Step 3: Start OpenVPN in background.
    #   `--pull-filter ignore redirect-gateway` stops the server from taking
    #   over the sandbox default route, otherwise the SDK control connection
    #   gets pulled into the tunnel and every later command times out. The VPN
    #   subnet routes are still installed.
    print("\nStarting OpenVPN tunnel...")
    sandbox.commands.run(
        f'nohup sudo openvpn --config {REMOTE_CONFIG} '
        f'--pull-filter ignore "redirect-gateway" '
        f"> {REMOTE_LOG} 2>&1 &",
        background=True,
    )

    # Wait for connection to establish
    print("Waiting for VPN connection to establish...")
    time.sleep(10)

    # Step 4: Verify connection - check if the tun0 interface exists
    print("\nVerifying OpenVPN connection...")
    response = sandbox.commands.run("ip addr show tun0 2>/dev/null || true")
    if "inet " in response.stdout:
        print("VPN tunnel interface (tun0) is up:")
        print(response.stdout)
    else:
        print("Warning: tun0 interface not found. Checking OpenVPN logs...")
        log = sandbox.commands.run(f"cat {REMOTE_LOG} 2>/dev/null || true")
        print(f"OpenVPN log:\n{log.stdout}")
        return sandbox

    print("\nOpenVPN connection established successfully.")
    return sandbox


def main() -> None:
    with open(OVPN_PATH, "r") as f:
        ovpn_config = f.read().strip()

    sandbox = setup_openvpn(ovpn_config)
    try:
        print("\nSandbox is connected. Press Ctrl+C to disconnect and kill it.")
        for _ in range(60):
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nInterrupted - shutting down.")
    finally:
        sandbox.kill()
        print("Sandbox killed")


if __name__ == "__main__":
    main()
```

```javascript Node.js theme={null}
// index.mts
// Connect a sandbox to an OpenVPN network using a `.ovpn` client
// configuration file (non-interactive).
import fs from 'fs'
import { fileURLToPath } from 'url'

import { PPIO } from 'ppio-sandbox'

// Path to the local .ovpn client profile in the parent directory.
const OVPN_PATH = fileURLToPath(new URL('../client1.ovpn', import.meta.url))
const REMOTE_CONFIG = '/tmp/client.ovpn'
const REMOTE_LOG = '/tmp/openvpn.log'

async function setupOpenVPN(ovpnConfig) {
  const ppio = new PPIO({ apiKey: process.env.PPIO_API_KEY })

  // Create the sandbox
  console.log('Creating sandbox...')
  const sandbox = await ppio.sandbox.create('base')
  console.log(`Sandbox created: ${sandbox.sandboxId}`)

  // Step 1: Install OpenVPN
  console.log('\nInstalling OpenVPN...')
  const install = await sandbox.commands.run(
    'sudo apt update && sudo apt install -y openvpn',
    { timeoutMs: 300_000 }
  )
  if (install.exitCode !== 0) {
    console.log(`Error installing OpenVPN: ${install.stderr}`)
    return sandbox
  }
  console.log('OpenVPN installed successfully.')

  // Step 2: Write the OpenVPN config file
  console.log('\nWriting OpenVPN configuration...')
  await sandbox.files.write(REMOTE_CONFIG, ovpnConfig)
  console.log(`Configuration written to ${REMOTE_CONFIG}`)

  // Step 3: Start OpenVPN in background.
  //   `--pull-filter ignore redirect-gateway` stops the server from taking
  //   over the sandbox default route, otherwise the SDK control connection
  //   gets pulled into the tunnel and every later command times out. The VPN
  //   subnet routes are still installed.
  console.log('\nStarting OpenVPN tunnel...')
  await sandbox.commands.run(
    `nohup sudo openvpn --config ${REMOTE_CONFIG} ` +
      `--pull-filter ignore "redirect-gateway" ` +
      `> ${REMOTE_LOG} 2>&1 &`,
    { background: true }
  )

  // Wait for connection to establish
  console.log('Waiting for VPN connection to establish...')
  await new Promise((r) => setTimeout(r, 10_000))

  // Step 4: Verify connection - check if the tun0 interface exists
  console.log('\nVerifying OpenVPN connection...')
  const res = await sandbox.commands.run('ip addr show tun0 2>/dev/null || true')
  if (res.stdout.includes('inet ')) {
    console.log('VPN tunnel interface (tun0) is up:')
    console.log(res.stdout)
  } else {
    console.log('Warning: tun0 interface not found. Checking OpenVPN logs...')
    const log = await sandbox.commands.run(`cat ${REMOTE_LOG} 2>/dev/null || true`)
    console.log(`OpenVPN log:\n${log.stdout}`)
    return sandbox
  }

  console.log('\nOpenVPN connection established successfully.')
  return sandbox
}

async function main() {
  const ovpnConfig = fs.readFileSync(OVPN_PATH, 'utf8').trim()
  const sandbox = await setupOpenVPN(ovpnConfig)
  try {
    console.log('\nSandbox is connected. Press Ctrl+C to disconnect and kill it.')
    await new Promise((r) => setTimeout(r, 60_000)) // keep running until this bounded wait ends
  } finally {
    await sandbox.kill()
    console.log('Sandbox killed')
  }
}

main().catch(console.error)
```

> [!WARNING]
>
> The `--pull-filter ignore "redirect-gateway"` flag stops the VPN server from taking over the sandbox default route. Without it, the SDK control channel can be routed into the tunnel and later commands can time out. VPN subnet routes are still installed, so the VPN network is reachable while the SDK keeps working.

OpenVPN runs with `background=True`, so it keeps running while further commands are issued. The tunnel is confirmed by checking that the `tun0` interface has an `inet` address.

## OpenVPN with a remote shell

Instead of driving the setup from the SDK, OpenVPN can be configured interactively from a remote shell with the CLI. This suits one-off connections, editing the `.ovpn` file by hand, and debugging the tunnel live.

**1. Connect to the sandbox**

Open an interactive remote shell into a running sandbox by its ID. This attaches the terminal to a shell inside the sandbox. See [ppio sandbox connect](https://docs.ppio.ai/sandbox/cli/connect.md) for the connect command.

**2. Install OpenVPN and tools**

Inside the remote shell, install OpenVPN along with `tmux` to keep the tunnel running in a background session, and `vim` to edit the config.

**3. Create or edit the .ovpn config**

Open the client profile in `vim`, paste in or adjust the OpenVPN client configuration, then save and exit. The file is saved as `/tmp/client.ovpn`.

**4. Start OpenVPN in a background tmux session**

Launch OpenVPN inside a detached `tmux` session so the tunnel keeps running independently of the shell. `-d` starts the session detached, `-s openvpn` names it, and the quoted command is what runs inside it.

Run the commands in order, starting from the local terminal:

```bash theme={null}
ppio sandbox connect <sandbox-id>
sudo apt update && sudo apt install -y openvpn tmux vim
sudo vim /tmp/client.ovpn
tmux new -d -s openvpn 'sudo openvpn /tmp/client.ovpn'
```

The tunnel now runs in the background. Keep using the current shell, disconnect, or manage the session as needed.

```bash theme={null}
# Attach to watch the OpenVPN output / logs
tmux attach -t openvpn
# Detach again without stopping it: press Ctrl+b then d

# Verify the tunnel interface is up
ip addr show tun0

# Stop the tunnel by killing the session
tmux kill-session -t openvpn
```

> [!NOTE]
>
> Running `tmux attach -t openvpn` reattaches to the session to view live OpenVPN logs. Press **Ctrl+b** then **d** to detach and leave it running.


## Related topics

- [ppio sandbox connect](https://docs.ppio.ai/sandbox/cli/connect.md)
- [Open an interactive terminal (PTY)](https://docs.ppio.ai/sandbox/terminal.md)
- [Manage sandboxes in the PPIO console](https://docs.ppio.ai/sandbox/console.md)


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