选择操作系统
WireGuard 最好在支持内核模块的操作系统上运行,以下是几种常见的操作系统选择:
- Linux:内置支持 WireGuard。
- Windows:需要额外安装 WireGuard 并配置虚拟机(如 WSL)。
- macOS:可以通过
brew安装 WireGuard。
安装 WireGuard
根据你的操作系统进行相应的安装:
在 Linux 系统上安装 WireGuard
-
更新并安装必要的软件包:
sudo apt update && sudo apt install wireguard
-
启用 WireGuard 内核模块:
sudo modprobe -w kgm wifi wireguard
-
创建 WireGuard 设定文件(
wg.conf):sudo wg create wg
配置 WireGuard 服务器
配置服务器的步骤如下:
-
启用 IP 转发:
sudo echo "post-up wg 0, add 172.16../24" >> /etc/wg/wg.conf sudo echo "post-up ip route 0.../ via 172.16..1" >> /etc/wg/wg.conf sudo echo "post-up ip route 169.254../16 via 172.16..1" >> /etc/wg/wg.conf sudo echo "post-up nat 172.16.. 172.16..1" >> /etc/wg/wg.conf
-
生成 WireGuard 服务器的公钥对:
sudo wg genkey | sudo tee /etc/wg/privkey | sudowg -p sudo wg pubkey | sudo tee /etc/wg/pubkey | sudowg -p
-
启动 WireGuard 服务器:
sudo wg-quick up wg
测试 WireGuard 服务器
使用以下命令验证服务器是否正常运行:
sudo wg show wg
让客户端连接到 WireGuard 服务器
客户端需要使用相同的 wg 接口,并使用服务器的公钥进行连接。
在 Linux 客户端上连接
-
安装 WireGuard:
sudo apt install wireguard
-
配置客户端的
wg.conf文件:sudo wg create wg sudo echo "peer 172.16..1" >> /etc/wg/wg.conf sudo echo "allowed-ip 0.../" >> /etc/wg/wg.conf
-
连接到服务器:
sudo wg-quick up wg
验证连接
在客户端上运行:
ping 172.16..1
确保能够成功连接到服务器。
故障排除
-
权限问题:确保你有足够的权限运行
wg-*命令,在 Debian/Ubuntu 上,你需要属于wireguard组:sudo adduser wireguard && sudo usermod -aG wireguard $USER
-
防火墙设置:确保防火墙允许 WireGuard 服务器接口的流量:
sudo ufw allow out on wg
-
路由问题:确保路由正确配置,尤其是默认网关。
高级配置
- 多点到点配置:如果你需要多个服务器连接到同一个客户端,可以在客户端的
wg.conf文件中添加多个peer。 - NAT 穿透:如果服务器在 NAT 后面,可以配置 NAT 穿透:
sudo wg-quick add-float 0.../
- 负载均衡:可以配置 WireGuard 服务器负载均衡,以提高性能:
sudo wg set peer 192.168.1.1:51820 metric 1: sudo wg set peer 192.168.1.2:51820 metric 2:
WireGuard 的配置相对简单,适合需要轻量级 VPN 连接的场景,通过以上步骤,你可以轻松搭建一个高性能的 WireGuard 服务器,并管理客户端连接。









