SSD Nodes Learn Hosting plans →
Guides Matt ConnorBy Matt Connor

Connect two VPS on a private network

Two VPS, one private network: a provider VPC, a WireGuard tunnel you own, or a managed mesh. Subnet choice, service binding, firewall rules and MTU included.

Can you connect two VPS on a private network?

Yes. Two VPS can be joined into one private network, where each machine reaches the other by a private address that the public internet cannot route. The way not to do it is the shortcut: bind PostgreSQL to 0.0.0.0, open port 5432 in the firewall, and trust the password. A database port on a public IP is found by scanners within hours of being opened, and after that one credential is the only thing between your data and the internet.

There are three ways to build the private link. Which one fits depends on where the two machines live.

  1. Your provider's private network or VPC (virtual private cloud). Often free and fast within one data center; cross-region peering can cost extra. Available when both VPS sit at the same provider, subject to its region and peering rules.
  2. A WireGuard tunnel you configure yourself. Encrypted, works between any two machines that can reach each other, about ten lines of config per side.
  3. A managed mesh such as Tailscale, or self-hosted Headscale. The answer when the machines are at different providers, when one has no public IP, or when you expect to add a third machine later.

Each option is set up below, followed by the parts that break after the setup works: subnet choice, service binding, firewall rules, MTU (maximum transmission unit) and what a reboot does.

Pick the tunnel subnet before you build anything

The private range you choose is painful to change later, because it ends up in config files, connection strings and firewall rules on both machines. Pick one that will not collide with a network either machine already uses.

A collision does not print an error. It is silent, because within the same routing table the kernel routes by the most specific match: if your tunnel claims 172.17.0.0/24 and Docker's default bridge already owns 172.17.0.0/16 on that host, the tunnel's /24 wins over the /16 for addresses in 172.17.0.x. Locally assigned addresses are exceptions: Linux normally checks the local table before the main table, so the Docker bridge address assigned to the host remains local. The tunnel keeps working, and it is the traffic the host sends to containers on those addresses that goes into the tunnel instead, so those containers stop answering. Run ip route show on both machines and pick a range that does not appear in either output.

Ranges worth avoiding: 192.168.0.0/24 and 192.168.1.0/24, which are what home and office routers hand out; 172.17.0.0/16, the Docker default bridge, along with the 172.18 and higher networks that Docker Compose creates for each project; 100.64.0.0/10, which Tailscale uses; and whatever range your provider allocates for its own private network. For a small setup 10.90.0.0/24 is a safe pick, and the examples below use it.

Option 1: your provider's private network or VPC

Most providers can attach a second network interface on a private range, often called a VPC (virtual private cloud). Pricing, region limits and encryption depend on the provider: Hetzner Networks are free and not automatically encrypted, while DigitalOcean charges for cross-datacenter VPC peering and AWS supports encryption in transit. Both VPS must be attached to private networks that the provider connects.

The interface may already have the private address assigned, as DigitalOcean Droplets do by default. Find the interface first.

ip -brief address show
ip route show default

Identify the private NIC (network interface card) by matching its address or MAC address to the provider's panel and networking documentation; an interface with no address is not a reliable identifier. Do not assume eth0. If the provider requires manual netplan configuration, use its assigned address, prefix and interface name in a file such as /etc/netplan/60-private.yaml:

network:
  version: 2
  ethernets:
    enp7s0:
      addresses:
        - 10.20.30.11/24
sudo chmod 600 /etc/netplan/60-private.yaml
sudo netplan apply
ip -brief address show enp7s0
ping -c 3 10.20.30.12

The interface should now show UP with the address you set, and the ping to the other machine's private address should answer in well under a millisecond when both are in the same region. Skip the chmod and netplan apply warns that the file permissions are too open, because a netplan file can hold secrets such as a wifi key.

What this protects you from. The public internet. A private address is not routable from outside, so a scanner never sees the port at all. What it does not protect you from. Anything already inside the provider's network. The scope varies, so read your provider's documentation: on some, a private address is reachable only from your own account, and on others every machine in that data center can reach it. Without provider encryption or application TLS, the traffic is in clear text, so anything that can capture packets on that segment reads your database rows. When the data matters, run option 2 over the private interface: point WireGuard's Endpoint at the private address and you get encryption on the short path.

Option 2: a WireGuard tunnel between the two VPS

WireGuard is a Layer 3 tunnel in the kernel, mainline since Linux 5.6, so Ubuntu 24.04 and Debian 13 need no extra module. Between two servers it is a point-to-point link: each side lists exactly one peer, and there is no NAT (network address translation) and no IP forwarding to set up. A peer is a public key plus the addresses that key may use, which is why WireGuard uses the association between public keys and AllowedIPs for routing and access control.

Say host A is the web server, at public IP 203.0.113.10, and host B is the database, at 198.51.100.20. Host A takes 10.90.0.1 inside the tunnel and host B takes 10.90.0.2. Run this on both machines:

sudo apt update && sudo apt install -y wireguard
sudo install -d -m 700 /etc/wireguard
sudo sh -c 'umask 077; wg genkey > /etc/wireguard/host.key'
sudo sh -c 'wg pubkey < /etc/wireguard/host.key > /etc/wireguard/host.pub'
sudo chmod 600 /etc/wireguard/host.key
sudo cat /etc/wireguard/host.pub

That last line prints the public key you paste into the other machine's config. The .key file never leaves the machine it was generated on. The privileged shell runs umask 077 before creating the private key through its redirection, so the new file is readable and writable only by root; the explicit chmod 600 also fixes permissions if the file already existed.

Write /etc/wireguard/wg0.conf on host A:

[Interface]
Address = 10.90.0.1/24
ListenPort = 51820
PrivateKey = <host A private key>

[Peer]
PublicKey = <host B public key>
AllowedIPs = 10.90.0.2/32
Endpoint = 198.51.100.20:51820
PersistentKeepalive = 25
Host B: the complete /etc/wireguard/wg0.conf
[Interface]
Address = 10.90.0.2/24
ListenPort = 51820
PrivateKey = <host B private key>

[Peer]
PublicKey = <host A public key>
AllowedIPs = 10.90.0.1/32
Endpoint = 203.0.113.10:51820
PersistentKeepalive = 25

Neither file holds the other machine's private key. Each side keeps its own private key and the other side's public key. Copy the public keys with sudo cat /etc/wireguard/host.pub, and leave the .key files where they are.

The /24 on Address sets the route for the whole tunnel subnet, which leaves room for a third machine later. AllowedIPs is a single /32 on each side, the one tunnel address the other machine owns. Inbound that list works as an access-control list: a decrypted packet whose source address is outside the peer's AllowedIPs is dropped, so a peer cannot claim to be some other address in your network. Both sides carry an Endpoint here because both have a public IP, which matters after a reboot: either machine can start the handshake, so the link returns without waiting for the other side to notice. The wider AllowedIPs, NAT and DNS rules live in the single-server WireGuard VPN setup, and a two-host link needs none of the router parts of that guide.

Open the port and start the interface, on both machines:

sudo ufw allow 51820/udp comment 'wireguard'
sudo systemctl enable --now wg-quick@wg0
sudo wg show
ping -c 3 10.90.0.2

wg show should list the peer with a latest handshake a few seconds old and non-zero transfer in both directions. A peer with no handshake line means nothing is arriving or nothing is accepted. Check UDP 51820 in your provider's network firewall, which is a separate control from ufw on most panels, and then check that the keys are not crossed: the [Peer] block must hold the other machine's public key. enable --now is the important half of that systemctl line, because a hand-run wg-quick up wg0 is gone after the next reboot, and kernel upgrades mean reboots.

Threat model. WireGuard authenticates and encrypts every packet, so the traffic stays private on any path: a provider network you do not control, or the public internet between two providers. It does nothing for a host that is already compromised, since the tunnel address is reachable from any process on either machine.

Option 3: a managed mesh for VPS at different providers

When the two machines are at different providers, a provider's private network stops being an option. Hand-built WireGuard still works. So does a managed mesh, which keeps the same WireGuard data plane and adds a coordination server that assigns addresses, distributes public keys, and gets a connection through NAT when one side has no public IP.

Tailscale runs that coordination server for you. Install it on both machines:

curl -fsSL https://tailscale.com/install.sh | sh
sudo tailscale up

sudo tailscale up prints an authentication URL. Open it, sign in, and the machine joins your tailnet. Then check both sides:

tailscale status
tailscale ip -4

Each machine gets one address in 100.64.0.0/10 on an interface called tailscale0, and tailscale status lists the other machine; connection type is shown for active traffic, while idle or unused peers need not show it. Run tailscale ping <other machine's Tailscale IP> to generate traffic, then check tailscale status again. Use those addresses exactly as you would the WireGuard ones. If the other machine shows relay, it is using a DERP relay, which generally offers lower throughput than a direct connection: on a VPS the cause is usually blocked UDP or a hard NAT, and getting a relayed Tailscale connection to go direct covers both. A peer-relay connection uses a configured relay device in your tailnet and is usually faster than DERP.

Two settings matter on a server. Node keys expire after 180 days by default, and an expired key stops connections to and from the machine, so use Disable Key Expiry on each server in the admin console. Key expiry is disabled by default for newly authenticated tagged devices. Expiry notifications are available through configured webhook subscriptions: nodeKeyExpiringInOneDay warns less than a day before expiry, and nodeKeyExpired reports a recent expiry. Access rules default to allowing all of your own devices to reach each other, which is fine for two servers and wrong the day a laptop joins. For an unattended build, create an auth key in the console and pass it with sudo tailscale up --auth-key=tskey-auth-... so the machine needs no browser step.

Threat model. Traffic is encrypted end to end between your two machines, and the coordination server never holds their private keys, so it cannot read your database traffic. It does hold metadata: which machines exist, which public keys they present, and which of them may talk to each other. If that is not acceptable, run the control plane yourself. Headscale is an open source implementation of the Tailscale control server and the clients stay the official ones. If the link later needs to reach a whole private range behind one machine instead of the machine itself, that job is advertising routes from a subnet router.

Bind the service to the private address, not 0.0.0.0

A private network is useless while the service still answers on the public interface. Check what is listening:

sudo ss -tlnp

0.0.0.0:5432 or *:5432 means the port is open on every address the machine has, including the public one. 10.90.0.2:5432 means it accepts connections addressed to 10.90.0.2, not only connections arriving through the tunnel. Linux treats IP addresses as belonging to the host, so traffic to that address can arrive through another interface if routing and firewall rules permit it. The interface firewall rule below supplies the tunnel restriction. For PostgreSQL, set this in postgresql.conf:

listen_addresses = '10.90.0.2, 127.0.0.1'

Then allow the peer, and only the peer, in pg_hba.conf:

host    appdb    appuser    10.90.0.1/32    scram-sha-256

Restart the service and run sudo ss -tlnp again to confirm the address changed. For MySQL the equivalent is bind-address = 10.90.0.2 in /etc/mysql/mysql.conf.d/mysqld.cnf. For MariaDB, put the same line in its server option file, such as /etc/mysql/mariadb.conf.d/50-server.cnf on Debian 13.

Containers are where this goes wrong most often, because Docker publishes ports on all addresses by default and writes its own iptables rules that ufw does not filter. Name the tunnel address in the port mapping:

services:
  db:
    image: postgres:17
    ports:
      - "10.90.0.2:5432:5432"

With a plain "5432:5432" the database is on the public IP and ufw will still report the port as denied, which is why a published Docker port stays reachable even when ufw says deny. Binding the published port to the tunnel address fixes the default publication on every host address; hosts with a route to that address can still reach it through other interfaces when forwarding is enabled. When both services run on one host, keep the database off ports: completely.

Firewall rules that trust the tunnel and nothing else

The rule you want says: allow this port on this interface, and nowhere else.

sudo ufw allow in on wg0 to any port 5432 proto tcp comment 'db from tunnel'
sudo ufw status verbose

ufw status verbose should show 5432 allowed only on wg0, with the default incoming policy still deny. An interface rule is easier to keep correct than a source-address rule, because WireGuard has already verified that a packet arriving on wg0 came from a peer holding the right key. The default-deny policy that all of this depends on is covered in the ufw firewall basics for a VPS. On Tailscale the interface is tailscale0, so the rule becomes sudo ufw allow in on tailscale0 to any port 5432 proto tcp. Tailscale's default netfilter mode also accepts traffic arriving on tailscale0, ahead of ufw's rules when using iptables, so restrict access with the tailnet policy rather than relying on this ufw rule to limit tailnet traffic to port 5432.

A provider private network has no tunnel to trust, so the rule has to name the source address instead: sudo ufw allow from 10.20.30.11 to any port 5432 proto tcp. That trusts anything able to put that source address on that segment, which is the reason option 1 on its own is weaker than the other two.

Test the path from the other machine:

sudo apt install -y netcat-openbsd
nc -vz 10.90.0.2 5432

succeeded! means the TCP connection works. Connection refused means no service accepted the connection, or a firewall actively rejected it, for example with a TCP reset. A hang that ends in a timeout can mean dropped packets, a routing problem or a server too busy to accept connections. Check the listening address with sudo ss -tlnp, then inspect host and provider firewall rules and the route before changing anything.

Encapsulation costs bytes. WireGuard wraps your packet in an outer IP header, a UDP header, its own 16-byte header and a 16-byte authentication tag, so the packet the tunnel can carry is smaller than the one the underlying link can carry. When the MTU is too high, the symptom is confusing: ping works, psql connects, then one query with a large result hangs forever. Small packets fit and large ones are dropped, sometimes with no ICMP message getting back to tell the sender why.

ChartBytes left inside a WireGuard tunnel, by underlying path
The data behind this chart
[
  {
    "label": "1500 path, IPv4 endpoint",
    "path_mtu": 1500,
    "wireguard_overhead": 60,
    "tunnel_mtu": 1440
  },
  {
    "label": "1500 path, IPv6 endpoint",
    "path_mtu": 1500,
    "wireguard_overhead": 80,
    "tunnel_mtu": 1420
  },
  {
    "label": "1450 path, IPv4 endpoint",
    "path_mtu": 1450,
    "wireguard_overhead": 60,
    "tunnel_mtu": 1390
  },
  {
    "label": "1400 path, IPv6 endpoint",
    "path_mtu": 1400,
    "wireguard_overhead": 80,
    "tunnel_mtu": 1320
  }
]

Those figures are arithmetic, not measurements: they count the outer headers and authentication tag, without optional padding or extra encapsulation. On an ordinary 1500-byte path with IPv4 endpoints, those headers and the tag add 60 bytes (20 outer IP, 8 UDP, 16 WireGuard, 16 authentication tag), which leaves 1440 bytes for your data. With IPv6 endpoints the outer header is 20 bytes larger and the budget falls to 1420. That second number is why wg-quick sets the interface MTU to the route MTU minus 80: 1420 is safe for either endpoint family. Where the provider's own network encapsulates as well, a VXLAN underlay at 1450 for example, the ceiling drops again, to 1390 in the third row, and to 1320 on the 1400-byte path in the last row.

Measure instead of guessing. From host A:

ping -M do -s 1392 -c 3 10.90.0.2

-M do forbids fragmentation and -s sets the payload size, so 1392 bytes of payload plus 8 bytes of ICMP header plus 20 bytes of IP header is exactly 1420. Replies mean 1420 works. When the size is larger than the interface allows, ping fails at once with a local error that names the MTU it hit:

ping: local error: message too long, mtu=1420

When replies stop at some packet size below 1420, set the working packet size (the successful -s value plus 28 bytes for IPv4) as MTU in the [Interface] section of both configs and restart:

MTU = 1380

Tailscale sets tailscale0 to 1280 on its own, the minimum any IPv6 path must carry; packet size problems can still require lowering a connected LAN's MTU or using TCP MSS clamping.

Will the tunnel make my database slower?

Encryption is not what costs you. WireGuard runs in the kernel, and on a current VPS CPU that work is small next to the network. Distance is what costs you. Every query waits one full round trip for its answer, so a page that runs 50 small queries one after another over a 30 ms link spends 1.5 seconds waiting on the network, whatever the database does.

Measure both machines before you move anything. Run iperf3 -s on host B, then from host A:

ping -c 20 10.90.0.2
iperf3 -c 10.90.0.2

Keep the application and its database close to each other, in the same region and preferably on the same provider's private network. A cross-provider tunnel is a good fit for the pairing where latency does not matter: an application server and a backup box, where the traffic is one large transfer at night rather than thousands of small queries during the day.

What happens when one side reboots

A reboot exposes ordering problems that never appear while you set things up by hand.

The tunnel does not come back. Only an enabled unit starts at boot. systemctl is-enabled wg-quick@wg0 must print enabled on both machines. The Tailscale package enables tailscaled for you, so there systemctl is-enabled tailscaled prints enabled after install.

The service starts before the tunnel and cannot bind. A database told to listen only on 10.90.0.2 can fail when wg0 does not exist yet, because at that moment the machine does not have that address. With the PostgreSQL configuration above, 127.0.0.1 is also listed, so PostgreSQL starts if it can bind loopback, warns about the unavailable tunnel address, and does not listen on that address until restarted after the tunnel is up. A fatal startup error occurs if none of its configured TCP/IP addresses can be opened.

Order the service after the interface. Confirm the unit name first with systemctl list-units 'postgresql*', then write a drop-in:

sudo install -d /etc/systemd/system/postgresql@17-main.service.d
sudo tee /etc/systemd/system/postgresql@17-main.service.d/after-wg.conf >/dev/null <<'EOF'
[Unit]
After=wg-quick@wg0.service
Wants=wg-quick@wg0.service
EOF
sudo systemctl daemon-reload

The blunt alternative is net.ipv4.ip_nonlocal_bind = 1, which lets a process bind an address the machine does not have. It allows the early bind, and no traffic arrives until the interface exists anyway, so prefer the ordering.

The application does not reconnect. Every open TCP connection across the tunnel dies when the far side reboots, and a connection pool that never tests a connection hands out dead ones. The application then fails its first query with server closed the connection unexpectedly or connection reset by peer, and often keeps failing until it is restarted. Turn on the pool's health check (pool_pre_ping=True in SQLAlchemy, and the equivalent test-on-borrow option elsewhere) rather than assuming the link never drops. Containers need the same attention on the host: a compose stack only returns after a reboot if its restart policy says so.

FAQ

Can I connect two VPS at different providers on a private network?

Yes, but not with a provider's private network, which only reaches machines inside that one provider. Use WireGuard between the two public IPs, or a managed mesh such as Tailscale. Both encrypt the traffic, which matters here because the packets cross the public internet. Expect the round trip time that the distance between the two data centers implies, and measure it with ping before you move a database to the far end.

Is a provider's private network encrypted?

Not always. Hetzner Networks do not automatically encrypt traffic, while AWS supports encryption in transit. A private address alone does not guarantee encryption. The scope also varies by provider: on some, only your own account can reach those addresses, and on others every machine in the same data center can. Check the provider's documentation, and when the data is sensitive, run WireGuard over the private interface. You keep the short path and add encryption.

Which private subnet should I use so it will not collide later?

Pick a /24 that nothing on either machine already uses, such as 10.90.0.0/24. Avoid 192.168.0.0/24 and 192.168.1.0/24, which home and office routers hand out, 172.17.0.0/16 and up, which Docker uses, 100.64.0.0/10, which Tailscale uses, and the range your provider allocates for its own private network. Run ip route show on both machines and choose a range that appears in neither.

Why does my database refuse connections over the tunnel?

A successful ping across the tunnel with nc -vz 10.90.0.2 5432 returning Connection refused points to either a missing listener or an active firewall rejection; ICMP ping does not test TCP port 5432. Run sudo ss -tlnp and read the address next to the port: 127.0.0.1:5432 accepts nothing from the network. A connection that hangs and then times out can indicate firewall drops, routing trouble or an overloaded server. Check the listener, route and host and provider firewall rules before adding a rule on wg0.

No. Forwarding and masquerading are for a machine that routes traffic on behalf of other machines. A two-host link carries only traffic addressed to the two hosts themselves, so it needs no change to net.ipv4.ip_forward and no NAT rule. Leave forwarding enabled if another service, such as Docker, needs it. You need forwarding for the tunnel only when one machine has to reach a further network sitting behind the other one.

Was this article useful?

#networking#wireguard#private-network#tailscale#multi-server