How to Set Up a WireGuard VPN on a Raspberry Pi

Turning your Raspberry Pi into a VPN server is a cost-effective way to secure your internet traffic and access your home network remotely. WireGuard is the modern choice—faster, simpler, and more secure than older protocols. This guide walks you through a straightforward setup using a Raspberry Pi 3 or newer running Raspberry Pi OS.

First, ensure your Pi is updated and has a static IP address. Open a terminal and run sudo apt update && sudo apt upgrade -y. Then install WireGuard: sudo apt install wireguard -y. You’ll also need to generate public and private keys for the server and each client.

Article illustration

Generate Keys and Configure the Server

Create a directory for WireGuard configs: sudo mkdir -p /etc/wireguard. Generate the server key pair:

cd /etc/wireguard
sudo umask 077
sudo wg genkey | sudo tee server_private.key | sudo wg pubkey | sudo tee server_public.key

Now create the server config file sudo nano /etc/wireguard/wg0.conf with this content:

[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <paste server_private.key>

Add a peer section for your first client (phone/laptop):

[Peer]
PublicKey = <client_public_key>
AllowedIPs = 10.0.0.2/32

Save and exit. Enable IP forwarding: sudo nano /etc/sysctl.conf and uncomment net.ipv4.ip_forward=1. Apply it: sudo sysctl -p.

Set Up the Client and Enable Routing

On your client device (e.g., a laptop), install WireGuard and generate a key pair. Create a client config:

[Interface]
Address = 10.0.0.2/24
PrivateKey = <client_private_key>

[Peer]
PublicKey = <server_public_key>
Endpoint = your-pi-public-ip:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

To route traffic through the Pi, you need to enable NAT/masquerade. Install iptables: sudo apt install iptables -y. Add these rules:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i wg0 -j ACCEPT
sudo iptables -A FORWARD -o wg0 -j ACCEPT

Save rules: sudo netfilter-persistent save. Then start WireGuard: sudo systemctl enable --now wg-quick@wg0.

Test the Connection

On your client, activate the VPN. Check connectivity by visiting whatismyip.com — it should show your Pi’s public IP. If it works, you’re securely tunnelling traffic through your home network.

Conclusion

Setting up a WireGuard VPN on a Raspberry Pi is a weekend project that yields permanent privacy and remote access benefits. Keep your Pi updated and monitor logs with sudo wg show for any issues. For advanced setups, consider adding a firewall or dynamic DNS.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *