WireGuard VPN 部署全流程

前置条件

  • 阿里云 ECS,2GB 内存,2核 CPU,40GB 存储,3Mbps 带宽
  • 已开通安全组(防火墙)允许 UDP 51820(或自定义端口)

服务器端配置

首先,安装 WireGuard 服务器端软件,

1
2
3
sudo apt update
sudo apt upgrade -a
sudo apt install -y wireguard wireguard-tools

然后,生成服务器密钥,生成路径为 /etc/wireguard/

1
wg genkey | tee /etc/wireguard/server_private_key | wg pubkey > /etc/wireguard/server_public_key

接着,创建配置文件 /etc/wireguard/wg0.conf

1
2
3
4
5
6
7
8
9
[Interface]
Address = 10.0.0.1/24
PrivateKey = <server_private_key> # 打开文件 server_private_key 查看
ListenPort = 51820 # 监听某一端口

# 客户端配置
[Peer]
PublicKey = <client_public_key> # 客户端添加隧道,将会自动生成公钥、私钥
AllowedIPs = 10.0.0.2/32 # 该客户端在服务器内部网段

再然后,开启 IP 转发,

启用 IP 转发:

1
2
sudo sysctl -w net.ipv4.ip_forward=1
sudo sysctl -w net.ipv6.conf.all.forwarding=1

为了永久生效,把配置写入 /etc/sysctl.conf 文件:

1
2
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv6.conf.all.forwarding=1" | sudo tee -a /etc/sysctl.conf

再接着,配置 NAT 转发,

ip a 查看公网网卡名后,配置 NAT:

1
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

eth0 替换为实际网卡名,对于阿里云服务器,实际网卡名为 eth0

最后,启动 WireGuard 并设置自启动,

1
2
sudo systemctl enable wg-quick@wg0
sudo systemctl start wg-quick@wg0

至此,WireGuard 服务器端的部署基本完成。

客户端配置

在官方网站或应用商店下载并安装 WireGuard 客户端。

打开 WireGuard → “添加隧道” → “添加空隧道” → 自动生成公钥、私钥

客户端配置示例如下:

1
2
3
4
5
6
7
8
9
[Interface]
PrivateKey = <client_private_key>
Address = 10.0.0.2/32 # 添加客户端在内网IP,以便服务器端配对
DNS = 223.5.5.5 # 阿里云的DNS,避免解析失败

[Peer]
PublicKey = <server_public_key>
AllowedIPs = 0.0.0.0/0 # 开启全局流量
Endpoint = <server_public_ip>:51820

如果你只想走 VPN 上网,不影响其他网络服务,如下设置(非常建议):

1
AllowedIPs = 0.0.0.0/1, 128.0.0.0/1

这样会把“全网流量”拆成两半路由进 VPN,让某些 IP 不走 VPN。

将客户端公钥加入服务器,在服务器 /etc/wireguard/wg0.conf 增加 [Peer]

1
2
3
[Peer]
PublicKey = <client_public_key> # 将自动生成的公钥复制过来
AllowedIPs = 10.0.0.2/32 # 与客户端配置保持一致

注意问题

1,安全组 UDP 51820 端口开放;

2,NAT 转发必须设置,否则客户端全局流量无法访问互联网;

3,IP 转发必须开启 net.ipv4.ip_forward=1

4,对于 DNS,全局 VPN 必须设置,否则域名解析失败;

5,AllowedIPs 设置。全局 VPN:0.0.0.0/0,内网 VPN:10.0.0.0/24(仅 VPN 内网访问);

6,当添加新的客户端后,执行 sudo systemctl restart wg-quick@wg0 重启服务。

特别注意

配置新设备后,一定要重启软件,重启软件,重启软件!!!