通过 tailscale 搭建自己的 vpn

通过 docker 部署 headscale 和 tailscale 搭建自己的 vpn 环境.

部署 headscale

参考 https://headscale.net/running-headscale-container

创建 headscale 会使用到的目录:

1
2
3
4
5
6
7
mkdir -p /path/headscale/config
mkdir -p /path/headscale/data

# 创建 db.sqlite 文件
touch /path/headscale/config/db.sqlite
# 获取模板配置文件
wget -O /path/headscale/config/config.yaml https://raw.githubusercontent.com/juanfont/headscale/main/config-example.yaml

查看一下配置文件修改需要的配置, 我没有域名直接使用的 ip, 需要注意的配置如下:

1
2
3
4
# 填写主机地址, 即外部连接服务器时使用的地址, 有nginx时一般就是 host_ip:80/443
server_url: http://<host_ip>:<port>
# headscale 实际监听的地址, 如果没有域名, 主机部署的时候可以和 server_url 是一样的
listen_addr: 0.0.0.0:8080

编写 docker-compose 配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
version: '3'
services:
headscale:
container_name: headscale
image: headscale/headscale:latest
ports:
- "<port>:8080"
cap_add:
- NET_ADMIN
- NET_RAW
- SYS_MODULE
sysctls:
- net.ipv4.ip_forward=1
- net.ipv6.conf.all.forwarding=1
restart: always
volumes:
- /path/headscale/config:/etc/headscale
- /path/headscale/data:/var/lib/headscale
command: ["headscale", "serve"]

创建用户:

1
docker exec headscale headscale user create <headscale_user>

这样服务端就配置好了.

客户端 tailscale

Linux

具体可以参考 https://tailscale.com/kb/1031/install-linux/

一般执行以下脚本安装并启用 tailscale 客户端:

1
2
curl -fsSL https://tailscale.com/install.sh | sh
systemctl start tailscaled

执行以下命令往 headscale 注册:

1
tailscale up --login-server http://<host_ip>:<port> --force-reauth

得到以下数据, 不要关掉程序:

1
2
3
4
5
~ sudo tailscale up --login-server http://<host_ip>:<port> --force-reauth

To authenticate, visit:

http://<host_ip>:<port>/register/nodekey:<token>

去 headscale 服务端认证, 执行以下命令:

1
docker exec headscale headscale nodes register --user <user> --key nodekey:<token>

等到客户端输出 Success, 说明节点加入成功, 可以看到虚拟网卡了:

1
2
3
4
xx: tailscale0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1280 qdisc fq state UNKNOWN group default qlen 500
link/none
inet 100.64.0.1/32 scope global tailscale0
valid_lft forever preferred_lft forever

iptables-ntf

tailscale 默认是使用 iptables 来控制添加虚拟网桥等命令, 在安装了 iptables-nft 的机器上就不使用, 需要添加 TS_DEBUG_USE_NETLINK_NFTABLES="true" 环境变量告诉 tailscale 使用 nft 的命令.

可以通过以下命令往 tailscaled 的默认环境变量中注入:

1
echo "TS_DEBUG_USE_NETLINK_NFTABLES=\"true\"" >> /etc/defaults/tailscaled

然后再通过 systemd 去启动 tailscaled

Android

直接 play 市场下载 tailscale 即可, 右上角三个点多点几次就可以出现配置服务器地址的配置项了.

dns

最近配置完 tailscale 之后, 发现连哪哪慢, 最后发现是因为 tailscale 会修改 dns 导致.直接执行以下命令禁止 tailscale 即可:

1
sudo tailscale up --login-server http://<ip>:<port> --accept-dns=false