WireGuard 是当前最容易理解 + 最快的 VPN 协议:4000 行内核代码,
配置就一个 .conf 文件。比 OpenVPN / IPsec 维护成本低一个数量级。
下面把两台公网服务器 gate.example.com(公网 IP 203.0.113.10)
和家里的 NAT 后机器接到同一虚拟网段 10.7.0.0/24。
1. 安装
# Debian 11+ / Ubuntu 20.04+
sudo apt install -y wireguard wireguard-tools
2. 生成密钥(两端各一份)
cd /etc/wireguard
umask 077
wg genkey | tee privatekey | wg pubkey > publickey
cat privatekey publickey
下面用占位符:
- SERVER_PRIV / SERVER_PUB
- PEER_PRIV / PEER_PUB
3. 服务端 gate 上 /etc/wireguard/wg0.conf
[Interface]
Address = 10.7.0.1/24, fd00:7::1/64
ListenPort = 51820
PrivateKey = SERVER_PRIV
# NAT 出口:让 peer 通过本机访问公网
PostUp = nft add table inet wg-nat; \
nft add chain inet wg-nat postrouting { type nat hook postrouting priority 100\; }; \
nft add rule inet wg-nat postrouting ip saddr 10.7.0.0/24 oifname "eth0" masquerade
PostDown = nft delete table inet wg-nat
[Peer]
PublicKey = PEER_PUB
AllowedIPs = 10.7.0.2/32, fd00:7::2/128
PersistentKeepalive = 25
4. 客户端 /etc/wireguard/wg0.conf
[Interface]
Address = 10.7.0.2/24, fd00:7::2/64
PrivateKey = PEER_PRIV
DNS = 1.1.1.1, 2606:4700:4700::1111
[Peer]
PublicKey = SERVER_PUB
Endpoint = 203.0.113.10:51820
AllowedIPs = 0.0.0.0/0, ::/0 # 全量流量走 VPN;只走内网就改 10.7.0.0/24
PersistentKeepalive = 25
PersistentKeepalive = 25 是 NAT 穿透的关键:每 25 秒发一个空包让上游
路由器 keep mapping。漏写 NAT 后端 5 分钟就掉。
5. 启用
两端都:
# 开 IP 转发(服务端必须)
echo 'net.ipv4.ip_forward=1' | sudo tee /etc/sysctl.d/99-wg.conf
echo 'net.ipv6.conf.all.forwarding=1' | sudo tee -a /etc/sysctl.d/99-wg.conf
sudo sysctl --system
sudo systemctl enable --now wg-quick@wg0
sudo wg show
6. 校验
# 在 peer 上
ping 10.7.0.1
ping fd00:7::1
curl ifconfig.me # 应当返回 gate 的公网 IP(说明全量走 VPN 了)
# 在 gate 上
sudo wg show
# peer: ...
# latest handshake: 5 seconds ago
# transfer: 10 KiB received, 12 KiB sent
latest handshake 没出现说明握手没成功;先排查防火墙是否放行 UDP/51820。
7. 加更多 peer
服务端 wg0.conf 追加 [Peer] 段;不需要 restart,热加:
sudo wg set wg0 peer NEW_PEER_PUB allowed-ips 10.7.0.3/32 persistent-keepalive 25
# 然后改 conf 保存让重启后还在
踩过的坑
AllowedIPs不是 "允许这个 peer 访问哪里",而是 路由表——告诉
内核"目标是这些 IP 的包应该走这个 peer"。客户端写0.0.0.0/0就把
默认路由抢了。- 服务端
AllowedIPs = 10.7.0.2/32不能写/24,否则只能挂一个 peer
—— 后加的 peer 路由会被前者抢掉。 wg-quick的PostUp/PostDown行如果失败,接口照常起来但 NAT
没工作,表现为"能 ping 服务端但 ping 不到外网"。用sudo journalctl -u wg-quick@wg0
看清楚 nft 报错。- IPv6 加进来后 DNS resolver 必须双栈,否则会出现 IPv4 通、IPv6 通但
解析慢的"假掉线"现象。
登录后参与评论。