Skip to content

🛡️ WireGuard VPN 搭建

最快、最简单、最省资源的 VPN。内核级性能,配置不过十几行。

WireGuard 是什么

WireGuard 是新一代 VPN 协议,2018 年并入 Linux 内核。对比传统 VPN:

特性WireGuardOpenVPNIPsec
代码量~4000 行~70000 行~400000 行
配置几行 conf几十行 + 证书极其复杂
速度极快(内核态)一般(用户态)快但配置难
漫游自动切换需重连支持
客户端全平台全平台平台限制
内核支持Linux 5.6+ 原生

一句话:能用 WireGuard 就别用别的。


安装

bash
# Ubuntu/Debian
sudo apt install wireguard -y

# 加载内核模块
sudo modprobe wireguard
lsmod | grep wireguard    # 确认加载

# 生成密钥对
wg genkey | tee privatekey | wg pubkey > publickey

服务端配置

bash
# 生成服务端密钥
sudo mkdir -p /etc/wireguard
cd /etc/wireguard
wg genkey | sudo tee server_private.key | wg pubkey | sudo tee server_public.key

/etc/wireguard/wg0.conf

ini
[Interface]
# 服务端 VPN 内网 IP
Address = 10.0.0.1/24
# 监听端口
ListenPort = 51820
# 服务端私钥
PrivateKey = <server_private_key>

# 开启 IP 转发(客户端通过服务端上网)
PostUp = sysctl -w net.ipv4.ip_forward=1
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

# 客户端1
[Peer]
PublicKey = <client1_public_key>
AllowedIPs = 10.0.0.2/32

# 客户端2
[Peer]
PublicKey = <client2_public_key>
AllowedIPs = 10.0.0.3/32

客户端配置

客户端的 wg0.conf

ini
[Interface]
# 客户端 VPN 内网 IP
Address = 10.0.0.2/24
# 客户端私钥
PrivateKey = <client_private_key>
# DNS(可选)
DNS = 114.114.114.114

[Peer]
# 服务端公钥
PublicKey = <server_public_key>
# 服务端公网 IP + 端口
Endpoint = 124.222.126.171:51820
# 哪些流量走 VPN
# 0.0.0.0/0 = 全部流量;10.0.0.0/24 = 只内网
AllowedIPs = 10.0.0.0/24
# NAT 穿透,每 25 秒发 keepalive
PersistentKeepalive = 25

启动与管理

bash
# 启动
sudo wg-quick up wg0

# 停止
sudo wg-quick down wg0

# 开机自启
sudo systemctl enable wg-quick@wg0

# 查看状态
sudo wg show

# 输出示例
# interface: wg0
#   listening port: 51820
#   peer: <client_pubkey>
#     endpoint: 1.2.3.4:51820
#     latest handshake: 5 seconds ago
#     transfer: 1.2 GiB received, 800 MiB sent

防火墙开放端口

bash
# ufw
sudo ufw allow 51820/udp

# iptables
sudo iptables -A INPUT -p udp --dport 51820 -j ACCEPT

常见场景

场景1:手机连回家里的服务器

手机装 WireGuard 客户端,配置同上。AllowedIPs = 10.0.0.0/24 只路由内网流量,不影响手机正常上网。

场景2:多机 GPU 集群组内网

  GPU服务器1 (10.0.0.1)

   WireGuard VPN (10.0.0.0/24)

  ├── GPU服务器2 (10.0.0.2)
  └── GPU服务器3 (10.0.0.3)

所有服务器通过 VPN 内网互通,无需公网 IP

场景3:异地办公连内网

ini
# 客户端 AllowedIPs = 0.0.0.0/0
# 所有流量走 VPN,在星巴克用公共 WiFi 也安全

排故

bash
# 握手失败
sudo wg show
# latest handshake: 0 seconds ago → 正常
# latest handshake: —              → 没连上

# 常见原因
# 1. 公钥/私钥不匹配
# 2. 防火墙没开 51820/udp
# 3. Endpoint IP 不对
# 4. 服务端没配 IP 转发(PostUp 那段)

# 查看内核日志
sudo dmesg | grep wireguard

🎯 本章要点

  • WireGuard:4000 行代码、内核级、配置几行搞定
  • 服务端核心:Interface 配 VPN IP + 私钥,Peer 配客户端公钥 + 允许 IP
  • 客户端核心:Interface 配 VPN IP + 私钥,Peer 配服务端公钥 + Endpoint
  • 启动:wg-quick up wg0;查状态:wg show
  • 不通先查防火墙 51820/udp + 公钥是否匹配 + IP 转发是否开启
加载练习题中...

有问题或补充?欢迎留言