Skip to main content

Web servers and networking · Intermediate · 17 min

Connect two servers privately with WireGuard

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · WireGuard tools 1.0.20250521 · PostgreSQL 18

You will link two Ubuntu 26.04 servers with an encrypted WireGuard tunnel, check both configurations before they go live, and move PostgreSQL onto the tunnel address so the database is never exposed on the public internet.

On this page

Two servers that need to talk to each other, an app and its database, a web server and a backup box, often sit in different places: one in a cloud region, one in an office or a different provider. Opening the database port to the internet and hoping the password holds is the wrong answer. WireGuard gives the two machines a private network of their own: each one gets a second address, traffic between those addresses is encrypted, and anything else that reaches the tunnel port without the right key is ignored.

WireGuard is built into the Linux kernel on Ubuntu 26.04, so all you install is the small wireguard-tools package with the wg and wg-quick commands. Each server has a key pair. You give each server the other's public key and say which tunnel addresses belong to it, and that is the whole trust model: there are no certificates, users or passwords.

In this tutorial you will connect two servers:

| | Server A (db1) | Server B (app1) |
|---|---|---|
| Where | Cloud, public IP 203.0.113.10 | Office, behind a NAT router |
| Tunnel address | 10.8.0.1 | 10.8.0.2 |
| Role | Listens on UDP 51820, runs PostgreSQL | Dials out to A, runs the app |

Replace 203.0.113.10 with server A's real public address everywhere; that range is reserved for documentation. The commands are labelled with the server they run on. Some run on both.

Server B behind a NAT router connects over the internet to server A on UDP port 51820. Each has a wg0 interface, 10.8.0.2 and 10.8.0.1, and PostgreSQL on A listens on 127.0.0.1 and 10.8.0.1 only
The finished setup: only UDP 51820 is open on A's public address

Step 1 · Install the WireGuard tools on both servers

On both servers:

Bash
sudo apt update
sudo apt install -y wireguard-tools

The kernel already has the WireGuard module, so there is no driver to build. The package ships wg (keys and live status), wg-quick (brings an interface up from a config file) and a systemd unit, wg-quick@.service, that starts a tunnel at boot.

Check it worked

On both servers:

Bash
wg --version

It prints something like wireguard-tools v1.0.20250521 - https://git.zx2c4.com/wireguard-tools/. To confirm the kernel side, run:

Bash
modinfo -F description wireguard

That prints a one-line description of the WireGuard module. If it says the module is not found, you are probably on a provider kernel without it; install linux-generic and reboot, or ask your provider.

Step 2 · Generate a key pair on each server

Each server makes its own private key, and the private key never leaves that server. Only the public key is copied across.

On both servers:

Bash
sudo install -d -m 700 /etc/wireguard
sudo sh -c 'umask 077; wg genkey > /etc/wireguard/private.key'
sudo sh -c 'wg pubkey < /etc/wireguard/private.key > /etc/wireguard/public.key'

umask 077 inside the root shell means private.key is created readable by root only, from its first byte. Running chmod afterwards would leave a short window where the key is readable by others. The second line derives the public key from the private one.

Check it worked

On both servers:

Bash
sudo ls -l /etc/wireguard
sudo cat /etc/wireguard/public.key

private.key shows -rw------- with owner root. public.key is a 44-character string ending in =, such as fE3oV0T...Xk0=. Copy each server's public key somewhere you can paste from, a note on your laptop is fine. You need A's key on B and B's key on A.

Step 3 · Write the configuration on server A

Server A has the public address, so it listens on a fixed port and waits. It does not need to know where B is: B is behind NAT and its public address and port can change, so A learns them from B's first valid packet.

On server A, store B's public key in a shell variable. Replace the text in quotes with the key you copied from server B:

Bash
PEER_PUBLIC_KEY='paste-server-B-public-key-here'

Now create the config file private and empty, then fill it. The if checks the key first: if it is not a complete WireGuard key, nothing is written and you see a message instead. Set the variable again and rerun the block:

Bash
if [ "$(printf '%s' "$PEER_PUBLIC_KEY" | base64 -d 2>/dev/null | wc -c)" -ne 32 ]; then
  echo "That is not a WireGuard public key. Copy it again."
  false
else
sudo install -m 600 /dev/null /etc/wireguard/wg0.conf
sudo tee /etc/wireguard/wg0.conf > /dev/null <<EOF
[Interface]
# db1
Address = 10.8.0.1/24
ListenPort = 51820
PrivateKey = $(sudo cat /etc/wireguard/private.key)

[Peer]
# app1
PublicKey = $PEER_PUBLIC_KEY
AllowedIPs = 10.8.0.2/32
EOF
fi

The heredoc is unquoted on purpose, so the shell fills in the private key and B's public key as it writes the file. The private key goes straight from one file into the other and never appears in your shell history.

What the keys mean:

  • Address is this server's address inside the tunnel. The /24 tells wg-quick to add a route for the whole 10.8.0.0/24 range through wg0, which leaves room for more servers later.
  • ListenPort is the UDP port A listens on. Without it, WireGuard picks a random port each time, and B would not know where to send.
  • AllowedIPs is the setting people most often misread. It is a routing table and an access list at once. When A sends a packet to 10.8.0.2, WireGuard looks up which peer owns that address and encrypts it for B. When a packet arrives and decrypts with B's key, WireGuard accepts it only if its source address is inside B's AllowedIPs. Use /32 so B can only ever speak as 10.8.0.2.
Server A's peer entry for B with AllowedIPs 10.8.0.2/32. When sending, a packet to 10.8.0.2 is encrypted for B and a packet to 10.8.0.9 matches no peer. When receiving, a packet from B with source 10.8.0.2 is accepted and one with source 10.8.0.50 is dropped
One setting, two jobs: where to send and whom to believe

Check it worked

wg-quick strip parses the file and prints only the parts the kernel will be given, with wg-quick's own keys such as Address removed. Filter out the private key so it does not end up on screen:

Bash
sudo wg-quick strip wg0 | grep -v '^PrivateKey'

You see ListenPort = 51820 under [Interface], then the [Peer] section with B's key and AllowedIPs = 10.8.0.2/32, and no Address line. If wg-quick warns that the file is world accessible, the install -m 600 line did not run; run it again before you continue.

Now prove the private key in the file is the one that matches A's public key. The two lines print the same string:

Bash
sudo wg-quick strip wg0 | awk '$1 == "PrivateKey" {print $3}' | wg pubkey
sudo cat /etc/wireguard/public.key

Step 4 · Write the configuration on server B

Server B is the one that starts the conversation, so its peer entry says where A lives. It also sends a small keepalive packet so the office router keeps the path open.

On server B, store A's public key. Replace the text in quotes with the key you copied from server A:

Bash
PEER_PUBLIC_KEY='paste-server-A-public-key-here'

Then write B's file. Replace 203.0.113.10 with server A's public address. The same key check runs first, and nothing is written if the key is incomplete:

Bash
if [ "$(printf '%s' "$PEER_PUBLIC_KEY" | base64 -d 2>/dev/null | wc -c)" -ne 32 ]; then
  echo "That is not a WireGuard public key. Copy it again."
  false
else
sudo install -m 600 /dev/null /etc/wireguard/wg0.conf
sudo tee /etc/wireguard/wg0.conf > /dev/null <<EOF
[Interface]
# app1
Address = 10.8.0.2/24
PrivateKey = $(sudo cat /etc/wireguard/private.key)

[Peer]
# db1
PublicKey = $PEER_PUBLIC_KEY
Endpoint = 203.0.113.10:51820
AllowedIPs = 10.8.0.1/32
PersistentKeepalive = 25
EOF
fi
  • Endpoint is A's public address and port. B needs it; A does not.
  • There is no ListenPort, so B uses a random source port. The NAT router maps it to whatever public port it likes, and A replies to that.
  • PersistentKeepalive = 25 sends an empty, encrypted packet every 25 seconds when the tunnel is otherwise quiet. NAT routers forget idle UDP mappings, often within a minute or two, and once that happens A has no way to reach B until B sends something. With the keepalive, A can start a connection to B at any time.

This layout also works when the office line uses carrier-grade NAT, as many LTE and some fibre connections in Nigeria, Kenya and elsewhere do: B dials out, so you need no port forward and no public IP at the office. On a metered or prepaid data plan the keepalive is cheap. Each one is a 32-byte WireGuard message plus IP and UDP headers, roughly 200 KB a day at most, and none are sent while real traffic is flowing.

If both servers have public addresses, add ListenPort = 51820 to B, open that port on B, and add an Endpoint for B on A. Then you can leave out PersistentKeepalive.

Check it worked

On server B:

Bash
sudo wg-quick strip wg0 | grep -v '^PrivateKey'
sudo wg-quick strip wg0 | awk '$1 == "PrivateKey" {print $3}' | wg pubkey
sudo cat /etc/wireguard/public.key

The first command shows a [Peer] section with A's key, Endpoint = 203.0.113.10:51820, AllowedIPs = 10.8.0.1/32 and PersistentKeepalive = 25. The last two lines print the same key.

Compare across the servers too: the PublicKey in A's [Peer] section is B's public.key, and the reverse. A swapped or mistyped key is the most common reason a tunnel never connects, and WireGuard does not log an error for it, because to WireGuard a packet with the wrong key is noise.

Step 5 · Open the port and bring the tunnel up

On server A, let WireGuard's port through UFW. Only UDP 51820 needs to be open to the world:

Bash
sudo ufw allow 51820/udp comment 'WireGuard'

If your provider has its own network firewall in front of the server, open UDP 51820 there as well. UFW cannot open a port that the provider blocks before traffic arrives.

Start the tunnel and turn it on at boot. On server A, then on server B:

Bash
sudo systemctl enable --now wg-quick@wg0

wg-quick@wg0 reads /etc/wireguard/wg0.conf, creates the wg0 interface, adds the address and the route, and loads the keys and peer.

Check it worked

On server B, ping A's tunnel address:

Bash
ping -c 3 10.8.0.1

Three replies come back. Then look at the live state on either server:

Bash
sudo wg show

You see something like this on A:

Text
interface: wg0
  public key: <A's public key>
  private key: (hidden)
  listening port: 51820

peer: <B's public key>
  endpoint: 198.51.100.77:40312
  allowed ips: 10.8.0.2/32
  latest handshake: 14 seconds ago
  transfer: 1.24 KiB received, 1.10 KiB sent

The endpoint is the office router's public address and the port it picked. latest handshake is the line that matters: if it is missing, the two servers have never agreed on keys. Work through it in this order: is UDP 51820 open at the provider and in UFW on A, is Endpoint on B the right address, and is each server's peer key the other server's public key.

Finally, from server A, ping B. This works because of the keepalive, even though B is behind NAT:

Bash
ping -c 3 10.8.0.2

Step 6 · Move PostgreSQL onto the tunnel address

Now use the tunnel. PostgreSQL on server A should accept connections from the app on B, and from nowhere else. You will make it listen on 10.8.0.1 as well as localhost, allow B's tunnel address in pg_hba.conf, and let port 5432 in on wg0 only.

If PostgreSQL is not installed on server A yet, install it from the Ubuntu archive. On server A:

Bash
sudo apt install -y postgresql

If you followed /tutorials/install-postgresql-18-on-ubuntu-26-04 and already have PostgreSQL 18, skip that line; the paths below are the same.

Add a settings file in PostgreSQL's conf.d folder, which Ubuntu's main config reads automatically, so you do not have to edit postgresql.conf. On server A:

Bash
sudo tee /etc/postgresql/18/main/conf.d/wireguard.conf > /dev/null <<'EOF'
listen_addresses = 'localhost,10.8.0.1'
EOF

Create the app's role and database. createuser asks for the new role's password twice, so it never appears on the command line. If you already made appuser and appdb in the install tutorial, skip these two lines:

Bash
sudo -u postgres createuser --pwprompt appuser
sudo -u postgres createdb --owner appuser appdb

Allow appuser to reach appdb from B's tunnel address only, with a password. Appending keeps your existing rules as they are:

Bash
echo 'host  appdb  appuser  10.8.0.2/32  scram-sha-256' | sudo tee -a /etc/postgresql/18/main/pg_hba.conf

There is a trap at boot. PostgreSQL starts if it can open at least one of its listen addresses, and only logs a warning for the rest. If it starts before wg0 exists, it quietly listens on localhost only, and the app on B cannot connect until someone restarts the database. Tell systemd to bring the tunnel up first:

Bash
sudo mkdir -p /etc/systemd/system/postgresql@18-main.service.d
sudo tee /etc/systemd/system/postgresql@18-main.service.d/wireguard.conf > /dev/null <<'EOF'
[Unit]
Wants=wg-quick@wg0.service
After=wg-quick@wg0.service
EOF

Wants= starts the tunnel if it is not running, and After= holds PostgreSQL back until wg-quick has finished creating the interface. Load the change, restart PostgreSQL, and open 5432 on the tunnel interface only:

Bash
sudo systemctl daemon-reload
sudo systemctl restart postgresql@18-main
sudo ufw allow in on wg0 from 10.8.0.2 to any port 5432 proto tcp comment 'PostgreSQL over WireGuard'

Check it worked

On server A, ask PostgreSQL what it is listening on and whether it accepted the new rule:

Bash
sudo -u postgres psql -c 'SHOW listen_addresses;'
sudo -u postgres psql -c "SELECT line_number, database, user_name, address, error FROM pg_hba_file_rules WHERE address = '10.8.0.2';"
sudo ss -tln 'sport = :5432'

listen_addresses is localhost,10.8.0.1. The pg_hba_file_rules query returns one row for your new line with an empty error column. ss lists 127.0.0.1:5432, [::1]:5432 (where IPv6 is on, as it is by default) and 10.8.0.1:5432, and no 0.0.0.0:5432 or [::]:5432. If the 10.8.0.1 line is missing, /var/log/postgresql/postgresql-18-main.log will have a warning like could not create listen socket for "10.8.0.1": the tunnel was down when PostgreSQL started.

On server B, connect across the tunnel. psql asks for appuser's password:

Bash
sudo apt install -y postgresql-client
psql -h 10.8.0.1 -U appuser -d appdb -c 'SELECT inet_server_addr();'

It prints 10.8.0.1. From any machine outside the tunnel, such as your laptop, the public address must refuse the database port:

Bash
nc -zv -w 3 203.0.113.10 5432

It times out or reports the connection refused. Port 5432 is reachable only through wg0, and only from 10.8.0.2.

Step 7 · Rotate a key or remove the tunnel

If a server's private key may have leaked, generate a new pair on that server, put its new public key into the other server's [Peer] section, and restart wg-quick@wg0 on both. The old key stops working the moment the other side no longer lists it.

To add a third server later, give it 10.8.0.3, add a [Peer] block for it on A with AllowedIPs = 10.8.0.3/32, and restart the tunnel on A. B only reaches the new server if you add a peer for it on B too, or route through A, which is what /tutorials/reach-a-private-network-from-your-laptop-with-wireguard sets up.

To remove everything this tutorial added, first stop and disable the tunnel on both servers:

Bash
sudo systemctl disable --now wg-quick@wg0

On server A, remove the firewall rules, the PostgreSQL settings and the boot ordering, then restart PostgreSQL so it goes back to localhost only. Delete the host appdb appuser 10.8.0.2/32 line from /etc/postgresql/18/main/pg_hba.conf with sudoedit first:

Bash
sudo ufw delete allow 51820/udp
sudo ufw delete allow in on wg0 from 10.8.0.2 to any port 5432 proto tcp
sudo rm /etc/postgresql/18/main/conf.d/wireguard.conf
sudo rm -r /etc/systemd/system/postgresql@18-main.service.d
sudo systemctl daemon-reload
sudo systemctl restart postgresql@18-main

The next command deletes the keys for good, and a deleted private key cannot be recovered. Make sure you are on the right server and no longer need this tunnel. On both servers:

Bash
sudo rm -r /etc/wireguard

Remove the tools you installed. On both servers:

Bash
sudo apt remove wireguard-tools

On server B, also remove the PostgreSQL client:

Bash
sudo apt remove postgresql-client

If you created appuser and appdb in this tutorial and no longer need them, drop them on server A. This deletes the database and every row in it for good, so take a backup with pg_dump first if anything in it matters:

Bash
sudo -u postgres dropdb appdb
sudo -u postgres dropuser appuser

Skip this if the role and database came from the install tutorial or another app still uses them.

Check it worked

After a rotation, sudo wg show on each server shows a fresh latest handshake and the new public key. After a removal, ip -br link show wg0 reports that the device does not exist, sudo ufw status no longer lists 51820, and sudo -u postgres psql -c 'SHOW listen_addresses;' prints localhost.

Next steps

Your two servers now share an encrypted private network, and the database answers only on it.

  • Give your laptop and phone a way into the same private network through a gateway: /tutorials/reach-a-private-network-from-your-laptop-with-wireguard.
  • Tighten the firewall further with UFW logging and rate limits: /tutorials/go-further-with-ufw-profiles-rate-limits-and-logging.
  • Plan a larger tunnel range for more servers: /tutorials/understand-ip-addresses-subnets-and-cidr.
  • Set up PostgreSQL from the PostgreSQL project's own repository: /tutorials/install-postgresql-18-on-ubuntu-26-04.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.