WireGuard部署,运维远程连接服务器方案
WireGuard 是一种轻量级、高性能的 VPN 协议,适合运维人员搭建远程连接服务器的安全通道。
本文以 Ubuntu 22.04 为例,从零开始演示服务端与客户端的完整配置,让你在 15 分钟内建立一条可用的加密隧道,并验证远程连接效果。
适用场景与准备工作
WireGuard 适合需要从外网安全访问内网服务器、数据库或管理后台的运维场景。
相比 OpenVPN,它配置更简单,内核态处理效率更高。
开始前请确认:
- 一台拥有公网 IP 的 Ubuntu 服务器(服务端),系统建议 20.04 或更高。
- 一台本地客户端(Windows/macOS/Linux 均可)。
- 服务器防火墙已放行 WireGuard 默认端口
51820/UDP。 - 拥有
sudo权限的 SSH 账号。
关键结论:WireGuard 通过 UDP 传输,需确保云服务商安全组和系统防火墙同时放行 51820/UDP,否则隧道无法建立。
安装 WireGuard 并生成密钥对
在服务端和客户端分别安装 WireGuard 工具。
Ubuntu/Debian 服务端执行:
sudo apt update
sudo apt install wireguard -y
生成服务端密钥(在服务端操作):
cd /etc/wireguard
umask 077
wg genkey | tee server_private.key | wg pubkey > server_public.key
生成客户端密钥(在客户端操作,Windows 可使用 WireGuard 官方客户端生成):
wg genkey | tee client_private.key | wg pubkey > client_public.key
记录以下四个值,后续配置需要用到:
- 服务端私钥(server_private.key)
- 服务端公钥(server_public.key)
- 客户端私钥(client_private.key)
- 客户端公钥(client_public.key)
配置服务端与客户端
在服务端创建 /etc/wireguard/wg0.conf,内容如下:
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <服务端私钥>
[Peer]
PublicKey = <客户端公钥>
AllowedIPs = 10.0.0.2/32
说明:
Address是服务端隧道内网 IP,客户端将使用10.0.0.2。AllowedIPs指定允许该客户端使用的隧道 IP。
在客户端新建配置文件 wg0.conf(Windows 客户端可直接在界面导入):
[Interface]
PrivateKey = <客户端私钥>
Address = 10.0.0.2/24
DNS = 8.8.8.8
[Peer]
PublicKey = <服务端公钥>
Endpoint = <服务器公网IP>:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
注意:AllowedIPs = 0.0.0.0/0 表示所有流量走隧道,若只想访问内网,可改为 10.0.0.0/24。
启动服务并放行防火墙
服务端启用并启动 WireGuard:
sudo systemctl enable wg-quick@wg0
sudo systemctl start wg-quick@wg0
检查接口状态:
sudo wg show
应看到 interface: wg0 及 peer 信息。
如果服务器使用 UFW 防火墙,放行端口:
sudo ufw allow 51820/udp
sudo ufw reload
同时确认云服务商控制台的安全组已允许 51820/UDP 入站。
验证远程连接与常见排错
客户端启动隧道后,在客户端执行:
ping 10.0.0.1
若能收到回复,说明隧道已通。
再测试通过隧道访问服务器内网服务,例如:
ssh user@10.0.0.1
常见问题:
- 握手失败:检查服务端
wg show是否有latest handshake,若无,确认 UDP 端口放行和 Endpoint IP 正确。 - 能 ping 通但无法上网:检查客户端
AllowedIPs和 DNS 设置,若走全局流量需开启 IP 转发。 - 服务端未开启 IP 转发:编辑
/etc/sysctl.conf,取消注释net.ipv4.ip_forward=1,执行sudo sysctl -p生效。
判断条件:如果 wg show 中 transfer 有持续增长的数据,说明隧道工作正常;
若只有发送没有接收,通常是防火墙或 NAT 问题。
长期维护建议
将 WireGuard 设为开机自启(已通过 systemctl enable 完成)。
定期检查 /etc/wireguard/wg0.conf 权限,建议保持 600。
新增客户端时,只需在服务端添加 [Peer] 段落并重启接口:
sudo systemctl restart wg-quick@wg0
最终效果:通过 WireGuard 部署,你获得了一条加密的远程连接通道,可安全运维服务器,且配置简洁、性能损耗低。