在没有公网的情况下,部署一个 WireGuard VPN 连接到公有云的服务器上,方便访问内网资源
但服务器通常安装了较多容器和服务,因此直装 WireGuard 可能会影响其他服务的运行
考虑使用 Docker 容器来部署 WireGuard ,以隔离其与其他服务的影响
以下实践基于 debian12
镜像,其他版本可能需要调整
构造 Wireguard 的 Dockerfile 如下:
FROM debian:12.7
# 使用代理(可选)
# ARG http_proxy
# ARG https_proxy
# ENV http_proxy=http://localhost:7890
# ENV https_proxy=http://localhost:7890
# 更改apt源为清华源(可选)
RUN sed -i.bak 's|http://deb.debian.org|http://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources && \
sed -i.bak 's|http://security.debian.org|http://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources
RUN apt-get update && \
apt-get install -y wireguard iproute2 iptables && \
apt-get clean
# CMD ["wg-quick", "up", "wg0", "&&", "tail", "-f", "/dev/null"]
说明:
- 增加 tail 命令是为了保持容器运行状态,避免容器退出
- 如果需要使用代理,可以取消注释相关行并设置代理地址
构建 Docker 镜像:
docker build -t wireguard:latest .
为了生成 WireGuard 的公密钥,先运行一个临时容器:
docker run --rm -it --entrypoint /bin/sh wireguard:latest
生成密钥对:
wg genkey | tee privatekey | wg pubkey > publickey
将生成的 privatekey
和 publickey
保存到本地文件中,稍后在配置文件中使用
接下来,创建 WireGuard 的配置文件 wg0.conf
,内容如下:
[Interface]
PrivateKey = 你的私钥
Address = 10.1.0.2/24
PostUp = iptables -t nat -A POSTROUTING -s 10.1.0.1/32 -j MASQUERADE
PostDown = iptables -t nat -D POSTROUTING -s 10.1.0.1/32 -j MASQUERADE
[Peer]
PublicKey = 服务端公钥
PresharedKey = 服务端密钥
Endpoint = 服务端地址
AllowedIPs = 10.1.0.0/24
PersistentKeepalive = 25
将上述配置文件保存为 wg0.conf
,并确保将 你的私钥
、服务端公钥
、服务端密钥
和 服务端地址
替换为实际值
最后,以 compose 文件的形式运行 WireGuard 容器:
services:
wireguard:
build: .
container_name: wireguard
cap_add:
- NET_ADMIN
- SYS_MODULE
sysctls:
- net.ipv4.ip_forward=1
volumes:
- ./wg0.conf:/etc/wireguard/wg0.conf:ro
restart: unless-stopped
command: /bin/sh -c "wg-quick up wg0 && tail -f /dev/null"
healthcheck:
test: ["CMD-SHELL", "wg show wg0 || exit 1"]
interval: 30s
timeout: 5s
retries: 3
最终目录如下:
.
├── Dockerfile
├── compose.yml
├── wg0.conf
├── privatekey
└── publickey
启动 WireGuard 容器:
docker-compose -f compose.yml up -d
这将启动 WireGuard 服务,并将配置文件挂载到容器中运行