Ubuntu部署Wireguard笔记

334 阅读2分钟

WireGuard VPN 服务器安装配置指南

1. 系统准备

# 更新镜像并安装WireGuard
apt update && apt install -y wireguard

# 开启IP转发
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p

image.png

2. 生成密钥对

# 创建配置目录
mkdir -p /etc/wireguard && chmod 0777 /etc/wireguard
cd /etc/wireguard
umask 077

# 生成服务器密钥
wg genkey | tee server_privatekey | wg pubkey > server_publickey

# 生成客户端密钥(可生成多个)
wg genkey | tee client1_privatekey | wg pubkey > client1_publickey

image.png

image.png

3. 服务端配置

# 创建配置文件(注意替换eth0为实际网卡名)
cat > wg0.conf <<EOF
[Interface]
PrivateKey = $(cat server_privatekey)
Address = 10.0.8.1/24
ListenPort = 50814
DNS = 8.8.8.8
MTU = 1420

# 流量转发规则(eth0需替换)
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
# 客户端1配置
PublicKey = $(cat client1_publickey)
AllowedIPs = 10.0.8.10/32
EOF

image.png

image.png

image.png

4. 启动服务

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

# 启动服务
wg-quick up wg0

# 检查状态
wg show

image.png

image.png

5. 客户端配置

# 生成客户端配置
cat > client1.conf <<EOF
[Interface]
PrivateKey = $(cat client1_privatekey)
Address = 10.0.8.10/32
DNS = 8.8.8.8
MTU = 1420

[Peer]
PublicKey = $(cat server_publickey)
Endpoint = [服务器公网IP]:50814
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
EOF

image.png

6. 多客户端配置

在服务端配置中追加新的Peer段:

# 生成新客户端密钥
wg genkey | tee client2_privatekey | wg pubkey > client2_publickey

# 追加到wg0.conf
cat >> wg0.conf <<EOF

[Peer]
# 客户端2配置
PublicKey = $(cat client2_publickey)
AllowedIPs = 10.0.8.11/32
EOF

# 重载配置
wg syncconf wg0 <(wg-quick strip wg0)

客户端使用说明

Windows:

  1. 安装官方WireGuard客户端
  2. 导入生成的client1.conf文件

image.png

Linux:

# 安装客户端
apt install wireguard

# 使用配置
wg-quick up ./client1.conf

关键注意事项:

  1. 防火墙需放行UDP 50814端口
  2. eth0需替换为服务器实际公网网卡名
  3. 每个客户端应有独立的IP地址
  4. MTU值可根据网络情况调整(默认1420)
  5. 配置文件需妥善保管,PrivateKey不可泄露

常用命令:

  • 查看连接状态:wg show
  • 临时关闭VPN:wg-quick down wg0
  • 查看运行日志:journalctl -u wg-quick@wg0 -f

image.png