LINUX NETWORKING / NETWORK NAMESPACES · 2026

How to Build a Per-Application VPN on Linux with Network Namespaces

A practical architecture for isolated routing, local and remote namespace chains, namespace-specific DNS, fail-closed traffic control, and reliable transport lifecycle management.

How to Build a Per-Application VPN on Linux with Network Namespaces

A system-wide VPN is straightforward because it makes one routing decision for the entire machine: it changes the default route and sends nearly all traffic through the same transport. A per-application VPN is more demanding because it must change the network environment only for selected processes while leaving the rest of the host untouched.

On Linux, the robust approach is usually not to layer increasingly complex policy-routing exceptions onto the host. Instead, give the application a separate network stack and manage it as an independent environment.

This article explains the architecture behind that approach: Linux network namespaces, veth routing, namespace-specific DNS, the tunnel underlay path, a fail-closed firewall, privilege separation, lifecycle management, and the tests needed to prove that traffic cannot silently fall back to the host path.

The central design rule is simple: keep the host network stable and move only the selected process into a separately managed network stack.

How can one Linux application use a VPN without routing the whole host?

The most robust approach is to create a dedicated network namespace for the application, connect it to the host with a veth pair, pin the VPN endpoint to the host-side underlay path, and then move the application's default route to a TUN or WireGuard interface. Keep DNS separate through /etc/netns/NAME/resolv.conf, and load a default-deny leak-prevention policy before starting the application.

Why use a network namespace instead of policy routing alone?

Several mechanisms can steer selected application traffic, but they create different isolation boundaries:

ApproachMain advantageMain limitationBest fit
Network namespaceIndependent routing, DNS, interfaces, sockets, port space, and firewall stateRequires privileged setup and complete lifecycle managementPer-application VPNs that need an explicit fail-closed guarantee
Policy routing with fwmarkLightweight and able to reuse the host network stackStill shares host DNS, interfaces, and parts of the firewall stateTraffic steering with a simple boundary and no need for a separate network environment
cgroup + eBPFFine-grained classification and policy by process groupMore complex to implement, verify, and maintain over timePlatforms that need dynamic authorization or granular traffic control
ContainerCan isolate files, processes, and resources in addition to networkingUsually heavier for desktop software or one existing applicationServices and workloads that need a complete isolated runtime

1. Start with the boundary and guarantees

Before creating interfaces or firewall rules, define what the environment must guarantee:

  • ordinary host applications retain the existing default route and resolver;
  • the selected application uses its own routing and DNS configuration;
  • protected traffic cannot fall back directly to the host uplink when the tunnel fails;
  • the application runs as its normal user, not as root;
  • transport configuration cannot execute arbitrary provider-supplied code within the privileged control plane;
  • startup, readiness checks, restarts, and cleanup behave deterministically;
  • several isolated application environments can coexist.

A network namespace provides network isolation, not a complete security sandbox. It does not isolate the filesystem, process tree, clipboard, desktop APIs, devices, or the shared kernel. That boundary should be stated explicitly.

2. Network namespaces are the isolation primitive

A Linux network namespace provides an independent network stack, including its own interfaces, routing tables, firewall state, sockets, port space, and related configuration. A child process normally inherits its parent’s network namespace; setns() can move the calling thread into another namespace, while ip netns exec can launch a command there.

A named namespace is typically represented by a bind mount under /var/run/netns/NAME. The namespace remains alive for as long as processes, open file descriptors, or other references still use it. Removing the name alone does not necessarily destroy the underlying namespace immediately.

At a minimum, namespace initialization should include:

ip netns add app-vpn
ip -n app-vpn link set lo up

Bringing up loopback is easy to overlook. Without it, applications that expect local sockets, local DNS stubs, or loopback services may fail in ways that look unrelated to routing.

3. Connect the namespace to the host with a veth pair

The namespace needs an underlay path before any tunnel can be established. A veth pair acts like a virtual Ethernet cable: one end stays on the host and the other moves into the namespace.

ip link add veth-app-host type veth peer name veth-app-ns
ip link set veth-app-ns netns app-vpn

ip addr add 10.203.0.1/30 dev veth-app-host
ip link set veth-app-host up
ip -n app-vpn addr add 10.203.0.2/30 dev veth-app-ns
ip -n app-vpn link set veth-app-ns up
ip -n app-vpn route add default via 10.203.0.1

The host must forward traffic from the host-side veth interface and usually apply source NAT on its physical uplink. Every application environment should receive a unique small subnet so that routes and cleanup rules cannot collide.

Per-application VPN architecture separating the protected overlay from the transport underlay
Application traffic uses the tunnel, while the tunnel process retains a separate underlay route through the veth, host forwarding, and NAT.

4. Separate the transport underlay from the protected data path

This is the most important routing detail.

The tunnel process must first reach its remote endpoint through the veth pair and the host uplink. Once the tunnel interface is up, the namespace’s default route is usually changed so that application traffic goes through the tunnel. If the endpoint route is not pinned to the veth gateway, the tunnel may try to route its own packets back into itself and disconnect.

The namespace therefore needs two logically different paths:

  • underlay: transport packets to the configured endpoint through the veth and host;
  • overlay: protected application traffic through a TUN device, a WireGuard interface, or another routed transport.

Resolve the transport endpoint before enforcing a strict firewall, add an explicit route to that address through the veth gateway, and only then move the default application route to the tunnel. If a hostname resolves to multiple addresses, every permitted endpoint address must be handled consistently.

5. Build the kill switch before launching the application

A kill switch is not a background monitor; it is a routing and firewall invariant that must exist before the protected process starts.

A practical namespace firewall starts from a default-deny policy and permits only:

  • loopback traffic;
  • established return traffic;
  • traffic to the transport endpoint through the veth underlay;
  • the minimum DNS access needed to resolve that endpoint, if resolution is not completed earlier;
  • application traffic through the tunnel interface;
  • optional local-network destinations that are explicitly part of the policy.

Direct application traffic through the veth must remain blocked. The application must not start until the rules are loaded and the tunnel data path has passed its readiness checks.

IPv6 must be part of the guarantee. If the tunnel and firewall policy cover only IPv4, IPv6 must either be disabled inside the namespace or filtered and routed with equivalent rules. Otherwise the architecture can fail open.

For production systems, nftables allows an entire ruleset to be replaced atomically. With iptables, installation order and cleanup must be controlled carefully so that a brief restart window cannot expose a direct path.

6. Keep DNS inside the namespace

Linux supports namespace-specific configuration files under /etc/netns/NAME/. For example:

/etc/netns/app-vpn/resolv.conf

ip netns exec creates the required mount view so that namespace-unaware applications see this file as the standard /etc/resolv.conf, without changing the host resolver.

DNS handling has two distinct phases:

  • bootstrap DNS: resolve the transport endpoint before the tunnel is online, or allow only a tightly scoped resolver path;
  • protected DNS: once the tunnel is ready, ordinary application DNS should follow the protected route.

VPN helper scripts that modify the host’s systemd-resolved configuration must be disabled or replaced with namespace-local logic. Applications using DNS over HTTPS still create ordinary network connections; those connections must also traverse the protected route.

7. Separate the privileged control plane from the application

Creating namespaces, interfaces, routes, and firewall rules requires administrative privilege. The application itself should not keep that privilege.

A safe launch sequence enters the namespace with administrative privileges, rebuilds a minimal environment, permanently drops privileges to the intended desktop user, and then executes the command directly. Avoid eval, shell-reconstructed commands, and unquoted command strings.

Transport profiles must be treated as untrusted input. Many VPN formats can reference scripts, plugins, external key files, management sockets, or provider-specific hooks. A per-application network manager should accept a restricted, declarative subset and reject directives that would execute arbitrary code as root.

8. Treat the environment as a state machine

The architecture is easier to reason about when startup is modeled as an ordered state machine:

  1. validate the configuration and allocate a unique namespace name and subnet;
  2. create the namespace and enable loopback;
  3. create and address the veth pair;
  4. configure host forwarding and NAT;
  5. write namespace-specific DNS configuration;
  6. load fail-closed firewall rules;
  7. start the transport backend;
  8. verify the interface, routes, DNS, and actual data flow;
  9. only then launch the application as its normal user.

Shutdown must reverse the process: stop or terminate applications running in the namespace, stop the backend, remove host rules, delete interfaces, and finally remove the namespace. Running processes can keep a namespace alive after its name is deleted, so they should be terminated before cleanup.

Template systemd units are a natural fit because dependencies, restart policies, logging, and per-environment instances become explicit. However, an active service is not necessarily a usable network path. Readiness checks should distinguish process state, handshake, interface creation, route installation, DNS, and external connectivity.

9. Multiple applications, GUI processes, and profile switching

Each independent environment should have a unique namespace name, veth pair, subnet, firewall rule set, configuration directory, and service instance. This allows a browser, crawler, build process, and messenger to use different transports simultaneously.

Desktop applications add a subtle problem: many enforce a single running instance. Launching a second command inside the namespace may only send a message to an existing host-side process, leaving the real network traffic outside the namespace. Use application-specific options such as a separate profile directory or a no-remote mode, and verify the PID’s actual network namespace rather than assuming that the launcher created a new process.

Fast switching between transports is easier when the namespace lifecycle is separated from the backend lifecycle. The long-lived boundary can remain stable while the tunnel is replaced, provided the kill switch stays closed during the transition.

10. Make the path observable and test failure explicitly

Standard Linux tools should be sufficient for inspecting the environment:

ip netns list
ip -n app-vpn addr
ip -n app-vpn route
ip netns exec app-vpn ss -tunap
ip netns exec app-vpn iptables -nvL --line-numbers
ip netns exec app-vpn curl -4 https://api.ipify.org

A useful test plan should verify that:

  • the host’s public address and resolver configuration remain unchanged;
  • the protected process uses the transport’s public exit address;
  • DNS queries follow the intended path;
  • killing the tunnel blocks traffic instead of falling back;
  • IPv6 cannot escape;
  • restarting the environment does not create a temporary open window;
  • stopping and removing the environment leaves no stale rules, processes, interfaces, or resolver files.

A successful VPN handshake is not sufficient evidence of a usable path. The backend may be running while provider-side policy, routing errors, DNS failures, MTU mismatches, or stale remote sessions still block real traffic.

Practical verification: prove that traffic cannot fall back to the host path

A running tunnel process or a successful handshake is not sufficient. Verification should compare the host path, the namespace path, and the failure behavior after the tunnel stops, without depending on a particular orchestration tool.

CheckExpected result
Host public exitRetains the original public address and is unaffected by the per-application VPN
Public exit inside the namespaceShows the exit address provided by the VPN or remote network
Namespace default routePoints to the TUN or WireGuard interface after the tunnel becomes ready
Application connection after tunnel shutdownFails; it must not fall back through the veth path to the host uplink
Host DNSRemains unchanged
Namespace DNSUses the independent configuration in /etc/netns/NAME/resolv.conf
IPv6 without equivalent protectionIs disabled inside the namespace so it cannot bypass an IPv4-only leak-prevention policy
State after environment shutdownLeaves no processes, interfaces, routes, firewall rules, or resolver files behind

The following generic sequence compares the paths. The third command uses an example service name and should be replaced with the tunnel-management command used by the implementation:

curl -4 https://api.ipify.org
ip netns exec app-vpn curl -4 https://api.ipify.org
systemctl stop vpn-backend@app-vpn.service
ip netns exec app-vpn curl -4 --max-time 5 https://api.ipify.org
Critical result: the final command must fail instead of returning the host's public address. Otherwise the fail-closed boundary has not been established.

11. Compose application environments into chains—locally and across hosts

Once each application namespace is treated as a managed network node, its underlay does not have to terminate at the host uplink. It can instead traverse another verified namespace or a gateway on a remote Linux host. This enables multi-hop routing without collapsing every application into one shared network stack.

Local chaining with a dedicated tunnel per application

application
  → downstream namespace
  → application-specific OpenVPN or WireGuard tunnel
  → veth inside the upstream namespace
  → upstream VPN tunnel
  → Internet

The downstream tunnel endpoint is reachable only through the upstream protected path. Forwarding, source NAT, and TCP MSS clamping belong inside the upstream namespace and must apply to its verified tunnel interface—not to its host-facing veth. If the upstream tunnel disappears, the downstream environment loses its underlay and traffic is dropped instead of falling back to the host path.

Chaining therefore requires more than adding another route. The control plane must reject direct and indirect cycles, start the downstream environment only after the upstream data path is ready, bind their lifecycles, and stop dependent environments in the correct order.

Child namespaces that share an upstream tunnel

A child namespace does not always need its own VPN session. It can keep its own namespace, resolver, firewall, process boundary, and lifecycle while forwarding through an already verified upstream tunnel. This pattern is useful when several applications need separate policies and observability but may share the same public exit.

application
  → isolated child namespace
  → veth inside the upstream namespace
  → existing upstream tunnel
  → Internet

The child has no fallback route to the host uplink. It can forward traffic only while the upstream tunnel is ready, and recovery belongs to the upstream environment rather than to a nonexistent child VPN process.

Routing through a remote Linux host

A remote exit adds a second host and a second control plane. The architectural principle remains the same: keep the application in a local namespace, carry its protected traffic to a gateway on the remote host, and route that traffic through an isolated remote exit namespace.

local process
  → local application namespace
  → local tunnel client
  → private or public transport to the remote host
  → remote gateway interface and policy routing
  → isolated remote exit namespace
  → provider OpenVPN or WireGuard tunnel
  → Internet

In a private design, the remote gateway can listen only on loopback and be reached through supervised SSH local port forwarding over an existing SSH service. This avoids exposing another public listener. In a public design, the gateway can accept a direct OpenVPN, WireGuard, stunnel, Cloak, or similar transport. The choice changes firewall exposure, throughput, failure modes, and operational dependencies, but not the namespace architecture behind the gateway.

Two underlays must remain reachable. The client-to-gateway transport must stay on the local host path, while the provider tunnel endpoint must stay on the remote host uplink. Neither protected default route may capture the control traffic that keeps its own tunnel alive.

Traffic arriving at the remote gateway should be classified by incoming interface or source policy and then forwarded into the remote exit namespace. That namespace then applies its own endpoint pinning, DNS policy, fail-closed firewall, and provider tunnel. The result is a chain of independently isolated data paths—not one tunnel process moved to another machine.

Distributed lifecycle management is part of the design. Both hosts need authenticated control channels, compatible policy and configuration, boot-time recovery, health checks, dependency-aware restarts, credential rotation, and ownership-scoped cleanup. If the inter-host transport or either tunnel fails, the local application path must remain closed while only the failed component is recovered.

Observe the whole chain, not only the final IP address

A useful topology report should show the source address selected by routing, the egress interface, default gateway, local transport, upstream environment, public exit address, remote gateway, remote exit namespace, and provider tunnel. Standard tools such as ip route get, ip netns exec, ss, firewall counters, service logs, and remote-host inspection should be enough to identify the hop at which a multi-stage path failed.

12. Common architecture failures

FailureUnderlying causeCorrective principle
The tunnel connects and immediately dropsThe endpoint follows the new tunnel default routePin the endpoint route to the veth underlay
Host DNS changesA backend helper updates global resolver stateUse /etc/netns/NAME/resolv.conf and reject global hooks
Traffic leaks during startupThe application starts before fail-closed rules existLoad the kill switch before backend and application launch
IPv6 bypasses the VPNOnly IPv4 routing and firewall rules were implementedImplement equivalent IPv6 policy or disable it in the namespace
Deleting the namespace name does not clean up the environmentProcesses or open file descriptors still hold references to itTerminate namespace processes before deletion
A GUI application still uses the host routeThe launcher reused an existing host-side processLaunch a separate application instance and verify the PID’s network namespace
The reported “online” status is misleadingA successful handshake was treated as proof of data flowTest routing, DNS, and real traffic separately

13. Reference implementation: nns-app

The architecture described in this article does not depend on any particular orchestration tool. It can be assembled directly with iproute2, nftables or iptables, systemd, OpenVPN or WireGuard, and a conventional process supervisor.

nns-app is a compact open-source reference implementation. Its current release implements direct application namespaces, child namespaces that share an upstream tunnel, local chains, fail-closed routing, namespace-specific DNS, lifecycle management, diagnostics, and remote-host exits. The repository provides working code that can be compared with the principles above; it is not required to use the architecture.

Supported platforms and current limitations are documented in the project README. Network namespaces isolate network state; neither this project nor the architecture itself replaces a filesystem, process, user, or device sandbox.

Source code and release history: github.com/Maximly/nns-app ↗

Implementation checklist

  • Define the exact isolation and fail-closed guarantees.
  • Create one namespace, veth pair, subnet, resolver, firewall, and service instance per environment.
  • Keep a pinned underlay route to the transport endpoint.
  • Move application traffic to the protected path only after the transport backend is ready.
  • Load the kill switch before any protected process can send traffic.
  • Handle IPv4 and IPv6 explicitly.
  • Drop privileges before executing the application.
  • Reject executable directives in imported profiles.
  • Test failures, restarts, and cleanup—not just the happy path.
  • Keep the namespace lifecycle independent of the transport backend.

Quick questions

Is a network namespace an application sandbox?

No. It isolates the network stack, not the filesystem, process tree, devices, clipboard, desktop APIs, or shared kernel. A complete sandbox requires additional mechanisms such as containers, user namespaces, filesystem isolation, or another application-security boundary.

How does the design stop fallback when the VPN disconnects?

Load a default-deny firewall inside the namespace before starting the application. Permit application traffic only on the protected interface, plus the minimum underlay traffic that the tunnel process needs to reach its remote endpoint. Do not rely on a monitoring process to detect and block leakage after it starts.

Why must the VPN endpoint route be pinned?

After the namespace default route moves to the tunnel, the remote endpoint must still use the underlay path. Otherwise the tunnel tries to send its own transport packets through itself, creating recursive routing and breaking connectivity.

Does the application need to run as root?

No. Only the control plane that creates namespaces, interfaces, routes, and firewall rules needs administrative privileges. After entering the namespace, it should permanently drop privileges and execute the application as its normal user.

Why can a graphical application still use the host network?

A single-instance application may forward the new launch request to an already running host-side process. Use a separate profile directory or a no-remote option where available, and inspect the network namespace of the PID that actually performs the network requests.

Can OpenVPN and WireGuard use the same overall architecture?

Yes. Both can fit the same namespace, veth, DNS, fail-closed firewall, privilege, and lifecycle framework. Endpoint resolution, interface creation, readiness checks, handshake state, and configuration validation still need backend-specific implementations.

References

OPEN SOURCE

Reference implementation: nns-app

Inspect a compact open-source implementation of namespace lifecycle, DNS isolation, fail-closed firewalling, privilege separation, systemd services, OpenVPN and WireGuard transports, and local or remote chaining.

Open the reference implementation ↗Discuss Linux networking work

LINUX NETWORKING ENGINEERING

Need a production-grade per-application network architecture?

KernelSoft designs and audits Linux networking, network-namespace isolation, VPN transports, firewall policy, high-speed data paths, and kernel-level integrations.

Discuss the architecture