Console9

How to set up a WireGuard VPN server on Ubuntu

Install and configure a WireGuard VPN server on Ubuntu with key generation, NAT, and persistent tunnels.

How to set up a WireGuard VPN server on Ubuntu

Install and configure a WireGuard VPN server on Ubuntu with key generation, NAT, and persistent tunnels.

Prerequisites

  • Ubuntu 20.04+ server with root or sudo access.
  • A public IP address or domain name.
  • UDP port 51820 open in the firewall.

Step-by-Step: Set Up a WireGuard Server on Ubuntu

  1. Install WireGuard:

    sudo apt update
    sudo apt install wireguard
  2. Generate the server key pair. WireGuard uses Curve25519 keys for encryption:

    wg genkey | sudo tee /etc/wireguard/server_private.key | wg pubkey | sudo tee /etc/wireguard/server_public.key
    sudo chmod 600 /etc/wireguard/server_private.key
  3. Create the server configuration at /etc/wireguard/wg0.conf:

    [Interface]
    PrivateKey = <SERVER_PRIVATE_KEY>
    Address = 10.0.0.1/24
    ListenPort = 51820
    PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
    
    [Peer]
    PublicKey = <CLIENT_PUBLIC_KEY>
    AllowedIPs = 10.0.0.2/32

    Replace eth0 with the server's public network interface name. The PostUp and PostDown rules enable NAT so clients can access the internet through the VPN.

  4. Enable IPv4 forwarding:

    echo "net.ipv4.ip_forward = 1" | sudo tee -a /etc/sysctl.conf
    sudo sysctl -p
  5. Start and enable the WireGuard interface:

    sudo systemctl enable --now wg-quick@wg0

How to Verify the VPN Server Is Running

sudo wg show wg0

The output shows the interface, listening port, and any connected peers with their last handshake time.