Chancel's blog

230 字 1 分钟阅读

在 Debian 12 上使用 Docker 部署 WireGuard VPN

  • Proxy
  • Deploy

在没有公网的情况下,部署一个 WireGuard VPN 连接到公有云的服务器上, 再在内网部署一个 Wireguard Peer,可以很方便访问内网资源

但内网的服务器安装了其他容器和服务,因此安装 WireGuard 会干扰其他服务的网络正常运行

借助 Docker 容器来部署 WireGuard Peer,以隔离其与其他服务的影响

构造 Wireguard 的 Dockerfile 如下:

FROM debian:bookworm-slim

# 更改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 openresolv && \
    apt-get clean

构建 Docker 镜像,不出错即可:

docker build -t wireguard:debian .

在服务器上获得的 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 服务,并将配置文件挂载到容器中运行

互动

留言

发表留言

暂无留言,来做第一个吧。