Tailscale + Headscale:自建免费内网穿透的正确姿势

内网穿透的三次进化

方案复杂度安全性成本
frp / ngrok一般(端口暴露)需公网 VPS
WireGuard 裸配高(手动配 peer)极高免费
Tailscale + Headscale极高免费

为什么选 Headscale

Tailscale 官方服务免费版限制 3 个用户、100 台设备。Headscale 是 Tailscale 控制面的开源实现,没有用户数和设备数限制,数据完全归你。

十分钟部署 Headscale

# 在一台有公网 IP 的 VPS 上(1C1G 就够)
mkdir -p /opt/headscale && cd /opt/headscale

cat > docker-compose.yml << 'EOF'
version: '3.5'
services:
  headscale:
    image: headscale/headscale:latest
    volumes:
      - ./config:/etc/headscale/
      - ./data:/var/lib/headscale
    ports:
      - "8080:8080"  # API
      - "9090:9090"  # Metrics
    command: headscale serve
    restart: unless-stopped

  headscale-ui:
    image: ghcr.io/gurucomputing/headscale-ui:latest
    ports:
      - "443:443"
    restart: unless-stopped
EOF

# 生成配置
wget https://raw.githubusercontent.com/juanfont/headscale/main/config-example.yaml
mv config-example.yaml config/config.yaml

# 修改关键配置
sed -i 's|server_url: http://.*|server_url: https://your-domain.com|' config/config.yaml
sed -i 's|listen_addr: 127.0.0.1:8080|listen_addr: 0.0.0.0:8080|' config/config.yaml

docker compose up -d

客户端接入

# 1. 在 Headscale 创建用户
docker exec headscale headscale users create daiyu

# 2. 注册设备
docker exec headscale headscale --user daiyu preauthkeys create --reusable --expiration 24h
# 输出: abc123... (复制这个 key)

# 3. 客户端连接(Windows/Mac/Linux/Android/iOS 全支持)
tailscale up --login-server https://your-domain.com --authkey abc123...

实战场景

场景一:远程开发

# 在家 SSH 到公司的开发机(不需要任何端口映射)
ssh user@100.x.x.x  # Tailscale 分配的 100.x.x.x 内网 IP

# VS Code Remote 直连
code --remote ssh-remote+user@100.x.x.x /path/to/project

场景二:家庭 NAS 远程访问

# 给 NAS 装 Tailscale 客户端
# 在手机/笔记本上直接访问 http://100.x.x.x:5000
# 安全:流量全程 WireGuard 加密,没有端口暴露在公网

场景三:Exit Node(出口节点)

# 把家里的树莓派设为 exit node
tailscale up --advertise-exit-node
# 在咖啡厅的笔记本上
tailscale up --exit-node=100.x.x.x
# 所有流量走家里网络——免费 VPN!

安全注意事项

  • Derp 中继服务器建议自建(国内到官方 Derp 延迟较高)
  • ACL 规则精细控制谁可以访问谁
  • 定期 rotate preauth keys
  • Headscale 建议放在反向代理(Caddy/Nginx)后面加 HTTPS

这套方案我从 2024 年用到现在,稳定、快速、零成本。再也不用为内网穿透花钱了。