WireGuard VPN Setup: A Private Network Between Your Servers

Build a hub-and-spoke WireGuard VPN between servers and devices, then use it to secure SSH and private services.

8 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

WireGuard VPN Setup: A Private Network Between Your Servers

Sooner or later you want a private network between your machines: a laptop that can reach a database without exposing it to the internet, servers that talk to each other over an encrypted link, or an SSH port that only you can see. A VPN does this, and WireGuard makes it unusually simple. It is built into the Linux kernel, uses modern cryptography, and a working setup is often under twenty lines of configuration per machine.

This guide builds a small VPN step by step, explains the one concept that confuses everyone (AllowedIPs), and shows how to use the tunnel to lock down SSH. It builds on the SSH, networking, and server hardening posts in this series.

Golden rule: give every device its own key pair, and treat AllowedIPs as both a routing table and a firewall for what each peer may send.

The Design We Will Build

We will use a hub-and-spoke layout. One server with a public IP address (the hub) listens for connections. Everything else connects to it, so laptops and servers behind home routers or NAT work without opening any ports on their side.

flowchart LR
    L["Laptop<br/>10.8.0.2"] <--> H["Hub server<br/>10.8.0.1<br/>public IP, UDP 51820"]
    A["App server<br/>10.8.0.3"] <--> H
    P["Phone<br/>10.8.0.4"] <--> H

Every device gets an address in a private VPN subnet, here 10.8.0.0/24. Pick a range that does not overlap with the networks you use at home or in the office. The very common 192.168.0.0/24 and 192.168.1.0/24 cause routing conflicts as soon as you connect from a home network that uses them.

How WireGuard Thinks

  • Each machine has a private key (secret, never shared) and a public key (given to the other side).

  • A VPN interface, usually wg0, has an address and a list of peers.

  • A peer is identified by its public key. There are no usernames, passwords, or certificates to manage.

  • It runs over UDP on a port you choose (51820 by convention).

  • It is quiet: it sends nothing when idle, and replies to no one who does not hold a known key.

AllowedIPs, explained once

AllowedIPs on a peer does two jobs at the same time:

  1. Outgoing: traffic to these addresses is sent through that peer (it works as a route).

  2. Incoming: packets from that peer are accepted only if their source address is in this list (it works as a filter).

Where

Peer entry

AllowedIPs

Meaning

On the hub

the laptop

10.8.0.2/32

Only the laptop's VPN address may come from this peer

On the laptop

the hub

10.8.0.0/24

Send VPN-subnet traffic to the hub

On the laptop

the hub (full tunnel)

0.0.0.0/0, ::/0

Send all internet traffic through the hub

A mistake in AllowedIPs is the cause of most "the tunnel is up but nothing works" problems. When in doubt, check this first.

1. Install WireGuard

sudo apt install wireguard           # Debian / Ubuntu
sudo dnf install wireguard-tools     # Fedora / RHEL-family (the kernel module is built in on modern kernels)

Open the UDP port on the hub's firewall, and in any cloud security group:

sudo ufw allow 51820/udp

2. Generate Keys

Run this on each machine, and keep the private key on that machine only:

umask 077
wg genkey | tee private.key | wg pubkey > public.key
cat public.key                      # this one is safe to share

The umask 077 makes the files readable only by you. You will paste each machine's private key into its own config file, and its public key into the other side's config.

3. Configure the Hub

Create /etc/wireguard/wg0.conf on the hub:

[Interface]
Address = 10.8.0.1/24
ListenPort = 51820
PrivateKey = <HUB_PRIVATE_KEY>

[Peer]
# laptop
PublicKey = <LAPTOP_PUBLIC_KEY>
AllowedIPs = 10.8.0.2/32

[Peer]
# app server
PublicKey = <APPSERVER_PUBLIC_KEY>
AllowedIPs = 10.8.0.3/32

Lock the file down, because it holds a private key:

sudo chmod 600 /etc/wireguard/wg0.conf

If peers should be able to reach each other through the hub (laptop to app server, for example), enable IP forwarding and allow forwarded traffic on the tunnel interface:

echo 'net.ipv4.ip_forward=1' | sudo tee /etc/sysctl.d/99-wireguard.conf
sudo sysctl --system
sudo ufw route allow in on wg0 out on wg0

4. Configure a Client

On the laptop, create /etc/wireguard/wg0.conf:

[Interface]
Address = 10.8.0.2/24
PrivateKey = <LAPTOP_PRIVATE_KEY>

[Peer]
PublicKey = <HUB_PUBLIC_KEY>
Endpoint = vpn.example.com:51820
AllowedIPs = 10.8.0.0/24
PersistentKeepalive = 25
  • Endpoint is the hub's public address and port. Only the client needs it, because the hub learns the client's address when the client connects.

  • PersistentKeepalive = 25 sends a small packet every 25 seconds, keeping NAT routers from forgetting the connection. Use it on any peer behind NAT.

The app server's config looks the same, with its own address (10.8.0.3/24) and private key.

5. Start It and Check

sudo wg-quick up wg0                   # bring the tunnel up
sudo wg show                           # status
ping -c 3 10.8.0.1                     # from the laptop: can it reach the hub?
sudo wg-quick down wg0                 # bring it down
sudo systemctl enable --now wg-quick@wg0     # start at boot (run this on every machine)

A healthy wg show on the hub looks like this:

interface: wg0
  public key: <hub public key>
  listening port: 51820

peer: <laptop public key>
  endpoint: 198.51.100.7:49382
  allowed ips: 10.8.0.2/32
  latest handshake: 41 seconds ago
  transfer: 1.20 MiB received, 3.04 MiB sent

The line to look for is latest handshake. If a peer shows no handshake at all, the two sides have not successfully talked yet. Remember that WireGuard is silent when idle, so a peer with no recent traffic may show an old handshake, and that is normal. Send a ping to trigger one.

6. Add More Peers

Adding a device means generating its keys, adding a [Peer] block on the hub, and giving the device a config. This script, run as root on the hub, automates that. It applies the change without dropping existing connections.

#!/usr/bin/env bash
# add-peer.sh NAME VPN_IP   (run as root on the hub, for example: ./add-peer.sh phone 10.8.0.4)
set -euo pipefail
umask 077

name=${1:?Usage: $0 NAME VPN_IP}
ip=${2:?Usage: $0 NAME VPN_IP}
endpoint="vpn.example.com:51820"          # the hub's public address

priv=$(wg genkey)
pub=$(printf '%s' "$priv" | wg pubkey)
server_pub=$(wg show wg0 public-key)

cat >> /etc/wireguard/wg0.conf <<EOF

[Peer]
# ${name}
PublicKey = ${pub}
AllowedIPs = ${ip}/32
EOF

wg syncconf wg0 <(wg-quick strip wg0)     # apply without restarting the interface

cat > "/root/${name}.conf" <<EOF
[Interface]
Address = ${ip}/24
PrivateKey = ${priv}

[Peer]
PublicKey = ${server_pub}
Endpoint = ${endpoint}
AllowedIPs = 10.8.0.0/24
PersistentKeepalive = 25
EOF

echo "Client config written to /root/${name}.conf. Copy it securely, then delete it."

The generated client file contains that device's private key. Move it over a secure channel (for example scp), and delete it from the hub afterward. Anyone who has the file can impersonate that device.

To remove a device, delete its [Peer] block from wg0.conf and run the same wg syncconf command.

For a phone, install the WireGuard app and import the config by scanning a QR code:

sudo apt install qrencode
qrencode -t ansiutf8 < /root/phone.conf

7. Put the Tunnel to Work

Keep SSH off the public internet

The most valuable use of a private network is hiding administrative services. Once the VPN works, allow SSH only from inside it:

sudo ufw allow in on wg0 to any port 22 proto tcp     # SSH only via the tunnel
# Test this FIRST: connect with  ssh [email protected]  over the VPN, in a second terminal.
sudo ufw delete allow OpenSSH                         # then remove the public SSH rule

Do not remove the public SSH rule until you have logged in through the tunnel in a second terminal and confirmed that it works. If the tunnel fails after you close the public port, you are locked out and will need your provider's web console.

Reach private services

Bind databases, dashboards, and admin panels to the VPN address instead of the public one, for example listen_addresses = '10.8.0.1' for PostgreSQL, and connect over 10.8.0.1 from your laptop. They never appear on the public internet at all.

Optional: send all traffic through the hub

Full-tunnel setup (route all internet traffic through the hub)

On the hub, enable forwarding (section 3) and add NAT rules to the [Interface] section of wg0.conf. Replace eth0 with the hub's public network interface (check with ip -br a):

PostUp   = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

On the client, change the peer's AllowedIPs and set a DNS server:

[Interface]
Address = 10.8.0.2/24
PrivateKey = <LAPTOP_PRIVATE_KEY>
DNS = 1.1.1.1

[Peer]
PublicKey = <HUB_PUBLIC_KEY>
Endpoint = vpn.example.com:51820
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 25

If wg-quick complains that resolvconf is missing, install it (sudo apt install resolvconf or openresolv). All of the client's traffic then appears to come from the hub's IP address, and the hub's bandwidth becomes your bandwidth.

8. Troubleshooting

No handshake appears. The UDP packets are not arriving. Check the hub's firewall and cloud security group for UDP 51820, and verify the client's Endpoint. On the hub, watch for traffic with sudo tcpdump -ni any udp port 51820 while the client connects. If nothing arrives, the problem is the network path. If packets arrive but no handshake follows, the keys are wrong.

The keys are wrong. The most common mistake is pasting the private key where the public key belongs, or swapping the two machines' keys. Each PublicKey line must hold the other side's public key, and PrivateKey is that machine's own secret. Compare with sudo wg show (its public key field must match what the other side has).

There is a handshake, but pings fail. Look at AllowedIPs on both sides. For peer-to-peer traffic through the hub, also confirm that net.ipv4.ip_forward is 1 on the hub, and that the firewall's forward rules allow traffic in and out of wg0.

It works from some networks but not others. The VPN subnet overlaps with the network you are on. Move the VPN to a less common range, such as 10.77.0.0/24.

Large transfers stall while small pings work. An MTU problem. WireGuard's default is usually 1420. Try MTU = 1380 in the [Interface] section, and test with ping -M do -s 1300 10.8.0.1. The networking cheat sheet in this series explains the technique.

DNS does not work through the tunnel. For a full tunnel, set DNS = in the client's [Interface], and install resolvconf or openresolv if wg-quick needs it. Confirm with resolvectl status.

Warning: /etc/wireguard/wg0.conf is world accessible. Run sudo chmod 600 /etc/wireguard/wg0.conf.

RTNETLINK answers: File exists or wg0 already exists. The interface is already up. Run sudo wg-quick down wg0 first.

The tunnel dies after a while behind NAT. Add PersistentKeepalive = 25 on the peer that sits behind NAT.

The hub's address changes. If the hub has a dynamic IP, use a DNS name in Endpoint. Note that WireGuard resolves it when the interface starts, so a changed address needs a restart of the tunnel on the clients.

Security Habits

  • One key pair per device, never shared and never copied between machines

  • Private keys and config files at mode 600, and never committed to Git

  • The narrowest AllowedIPs that does the job (use /32 for single hosts)

  • Revoke a lost device immediately by deleting its [Peer] block

  • Firewall rules that allow administrative services only on wg0

  • Access to the hub's own SSH secured, with a console fallback kept in mind

  • A written record of which address and key belong to which device

  • Keys rotated when staff or devices change

Quick Reference

KEYS       umask 077; wg genkey | tee private.key | wg pubkey > public.key
CONFIG     /etc/wireguard/wg0.conf (chmod 600)   [Interface] Address, ListenPort, PrivateKey
           [Peer] PublicKey, AllowedIPs, Endpoint (client side), PersistentKeepalive = 25
CONTROL    wg-quick up|down wg0     systemctl enable --now wg-quick@wg0     wg show
APPLY      wg syncconf wg0 <(wg-quick strip wg0)    (no downtime)
FIREWALL   ufw allow 51820/udp     net.ipv4.ip_forward=1     ufw route allow in on wg0 out on wg0
DEBUG      wg show (latest handshake)    tcpdump -ni any udp port 51820    check AllowedIPs, MTU, overlapping subnets

Final Thoughts

WireGuard's appeal is how little there is to it: a key pair per machine and a short list of peers. The trade-off is that it deliberately leaves out things like user accounts, access policies beyond AllowedIPs, and automatic discovery of devices. For a handful of servers and a few laptops, that simplicity is a strength. If you later need device management, per-user rules, and NAT traversal for a larger team, tools built on top of WireGuard, such as Tailscale or Headscale, add those layers while keeping the same underlying protocol.

Try it this week with two machines: a hub with a public IP and any laptop. Get a successful handshake, ping across the tunnel, then restrict SSH to it. Once you have a private network that only your own devices can reach, you will want to move more of your administrative surface behind it.

Comments0

Log in to join the discussion.

No comments yet.

Sanju Singh

Read articles by this author.

Subscribe to Sanju Singh's newsletter

Get the articles this author chooses to send by email.