SiamCafe.net Blog
Technology

Tailscale Mesh Edge Computing — สร้าง Mesh VPN สำหรับ Edge Devices

tailscale mesh edge computing
Tailscale Mesh Edge Computing | SiamCafe Blog
2025-10-29· อ. บอม — SiamCafe.net· 1,136 คำ

Tailscale คืออะไร

Tailscale เป็น mesh VPN ที่สร้างบน WireGuard protocol ทำให้เชื่อมต่ออุปกรณ์ต่างๆ เข้าด้วยกันเป็น secure private network โดยไม่ต้อง configure firewall rules หรือ port forwarding ใช้ peer-to-peer connections ตรงระหว่างอุปกรณ์ ไม่ต้องผ่าน central server

จุดเด่นของ Tailscale ได้แก่ Zero-config VPN ติดตั้งง่ายไม่ต้อง configure เอง, WireGuard-based เร็วและปลอดภัย, NAT traversal ทำงานผ่าน NAT/firewall ได้โดยอัตโนมัติ, MagicDNS ใช้ชื่อ hostname แทน IP, ACLs กำหนด access control ละเอียด, SSO integration ใช้ Google, Microsoft, GitHub login

สำหรับ Edge Computing Tailscale ช่วยเชื่อมต่อ edge devices ที่กระจายอยู่หลายที่เข้าด้วยกัน ทำให้จัดการ deploy, monitor และ maintain edge infrastructure ได้ง่าย ไม่ต้อง expose services ให้ public internet

ติดตั้งและตั้งค่า Tailscale

Setup Tailscale บนอุปกรณ์ต่างๆ

# === Tailscale Installation ===

# 1. Linux (Ubuntu/Debian)
curl -fsSL https://tailscale.com/install.sh | sh
sudo tailscale up

# With specific options:
sudo tailscale up --advertise-routes=10.0.0.0/24 --accept-dns=true

# 2. Docker
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
  tailscale:
    image: tailscale/tailscale:latest
    container_name: tailscale
    hostname: edge-node-01
    environment:
      - TS_AUTHKEY=tskey-auth-xxxxx
      - TS_STATE_DIR=/var/lib/tailscale
      - TS_EXTRA_ARGS=--advertise-tags=tag:edge --advertise-routes=172.16.0.0/24
    volumes:
      - tailscale-state:/var/lib/tailscale
      - /dev/net/tun:/dev/net/tun
    cap_add:
      - NET_ADMIN
      - SYS_MODULE
    restart: unless-stopped
    network_mode: host

  app:
    image: myapp:latest
    network_mode: "service:tailscale"
    depends_on:
      - tailscale

volumes:
  tailscale-state:
EOF

docker-compose up -d

# 3. Kubernetes (Operator)
# Install Tailscale Kubernetes operator
helm repo add tailscale https://pkgs.tailscale.com/helmcharts
helm repo update

cat > values.yaml << 'EOF'
oauth:
  clientId: "your-oauth-client-id"
  clientSecret: "your-oauth-client-secret"
apiServerProxyConfig:
  mode: "true"
EOF

helm install tailscale-operator tailscale/tailscale-operator \
  -n tailscale --create-namespace -f values.yaml

# Expose a service via Tailscale
# Add annotation to Service:
# metadata:
#   annotations:
#     tailscale.com/expose: "true"
#     tailscale.com/hostname: "my-k8s-service"

# 4. Raspberry Pi / ARM
curl -fsSL https://tailscale.com/install.sh | sh
sudo tailscale up --authkey=tskey-auth-xxxxx --hostname=edge-pi-01

# 5. Auth Key Generation (for automated setup)
# Admin Console > Settings > Keys > Generate auth key
# Options:
# - Reusable: Yes (for multiple devices)
# - Ephemeral: Yes (auto-cleanup when offline)
# - Pre-approved: Yes (skip admin approval)
# - Tags: tag:edge

echo "Tailscale installed on all platforms"

สร้าง Mesh Network

สร้าง mesh network สำหรับ edge computing

#!/usr/bin/env python3
# mesh_network.py — Tailscale Mesh Network Management
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("mesh")

class TailscaleMeshManager:
    def __init__(self, tailnet):
        self.tailnet = tailnet
        self.nodes = []
    
    def register_node(self, hostname, node_type, location, tags):
        node = {
            "hostname": hostname,
            "tailscale_ip": f"100.{64 + len(self.nodes)}.0.{len(self.nodes) + 1}",
            "type": node_type,
            "location": location,
            "tags": tags,
            "status": "online",
            "os": "linux",
            "routes": [],
        }
        self.nodes.append(node)
        return node
    
    def get_topology(self):
        """Get mesh network topology"""
        connections = []
        for i, node_a in enumerate(self.nodes):
            for j, node_b in enumerate(self.nodes):
                if i < j:
                    connections.append({
                        "from": node_a["hostname"],
                        "to": node_b["hostname"],
                        "type": "direct" if node_a["location"] != node_b["location"] else "local",
                        "latency_ms": 5 if node_a["location"] == node_b["location"] else 45,
                    })
        
        return {
            "tailnet": self.tailnet,
            "total_nodes": len(self.nodes),
            "nodes_by_type": self._count_by("type"),
            "nodes_by_location": self._count_by("location"),
            "connections": len(connections),
            "topology": connections[:10],
        }
    
    def _count_by(self, field):
        counts = {}
        for node in self.nodes:
            val = node[field]
            counts[val] = counts.get(val, 0) + 1
        return counts
    
    def generate_acl_policy(self):
        """Generate Tailscale ACL policy"""
        return {
            "acls": [
                {
                    "action": "accept",
                    "src": ["tag:admin"],
                    "dst": ["*:*"],
                    "comment": "Admins can access everything",
                },
                {
                    "action": "accept",
                    "src": ["tag:edge"],
                    "dst": ["tag:cloud:443,8080", "tag:monitoring:9090"],
                    "comment": "Edge nodes can reach cloud services and monitoring",
                },
                {
                    "action": "accept",
                    "src": ["tag:cloud"],
                    "dst": ["tag:edge:22,8080"],
                    "comment": "Cloud can SSH and deploy to edge nodes",
                },
                {
                    "action": "accept",
                    "src": ["tag:monitoring"],
                    "dst": ["tag:edge:9100,9090", "tag:cloud:9100,9090"],
                    "comment": "Monitoring can scrape metrics from all nodes",
                },
            ],
            "tagOwners": {
                "tag:admin": ["group:admins"],
                "tag:edge": ["group:devops"],
                "tag:cloud": ["group:devops"],
                "tag:monitoring": ["group:devops"],
            },
        }

mesh = TailscaleMeshManager("mycompany.ts.net")

# Register nodes
mesh.register_node("cloud-api-01", "cloud", "bangkok-dc", ["tag:cloud"])
mesh.register_node("cloud-api-02", "cloud", "bangkok-dc", ["tag:cloud"])
mesh.register_node("edge-bkk-01", "edge", "bangkok-store", ["tag:edge"])
mesh.register_node("edge-cnx-01", "edge", "chiangmai-store", ["tag:edge"])
mesh.register_node("edge-hdy-01", "edge", "hatyai-store", ["tag:edge"])
mesh.register_node("monitor-01", "monitoring", "bangkok-dc", ["tag:monitoring"])

topology = mesh.get_topology()
print("Topology:", json.dumps(topology, indent=2))

acls = mesh.generate_acl_policy()
print("\nACLs:", json.dumps(acls["acls"], indent=2))

Edge Computing กับ Tailscale

Deploy edge computing workloads ผ่าน Tailscale

# === Edge Computing with Tailscale ===

# 1. Edge Deployment Architecture
# ===================================
# Cloud (Bangkok DC):
#   - API Gateway
#   - Central Database
#   - ML Model Registry
#   - Monitoring (Prometheus + Grafana)
#
# Edge (Each Store):
#   - Local API server
#   - Redis cache
#   - ML inference engine
#   - Data collector
#
# All connected via Tailscale mesh:
#   - Edge → Cloud: sync data, pull models
#   - Cloud → Edge: deploy updates, manage
#   - Edge → Edge: (not needed, blocked by ACL)

# 2. Edge Node Setup Script
cat > setup_edge.sh << 'BASH'
#!/bin/bash
set -e

HOSTNAME=$1
AUTH_KEY=$2

echo "Setting up edge node: $HOSTNAME"

# Install Tailscale
curl -fsSL https://tailscale.com/install.sh | sh
tailscale up --authkey=$AUTH_KEY --hostname=$HOSTNAME --advertise-tags=tag:edge

# Install Docker
curl -fsSL https://get.docker.com | sh
usermod -aG docker $USER

# Deploy edge services
cat > /opt/edge/docker-compose.yml << 'EOF'
version: '3.8'
services:
  edge-api:
    image: registry.ts.net/edge-api:latest
    ports:
      - "8080:8080"
    environment:
      - CLOUD_API=http://cloud-api-01:8080
      - REDIS_URL=redis://redis:6379
    restart: always

  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data
    restart: always

  node-exporter:
    image: prom/node-exporter:latest
    ports:
      - "9100:9100"
    restart: always

  data-sync:
    image: registry.ts.net/data-sync:latest
    environment:
      - CLOUD_DB=postgresql://cloud-db-01:5432/main
      - SYNC_INTERVAL=300
    restart: always

volumes:
  redis-data:
EOF

cd /opt/edge && docker-compose up -d

echo "Edge node $HOSTNAME ready"
BASH

chmod +x setup_edge.sh

# 3. Remote Management via Tailscale
# ===================================
# SSH to any edge node:
ssh edge-bkk-01  # Uses MagicDNS

# Deploy update to all edge nodes:
for node in edge-bkk-01 edge-cnx-01 edge-hdy-01; do
  echo "Deploying to $node..."
  ssh $node "cd /opt/edge && docker-compose pull && docker-compose up -d"
done

# Check status of all edge nodes:
tailscale status

# 4. Subnet Router (Access local network)
# ===================================
# On edge node, advertise local subnet:
tailscale up --advertise-routes=192.168.1.0/24

# In admin console: approve the route
# Now cloud servers can reach 192.168.1.x via edge node

echo "Edge computing configured"

Security และ Access Control

Security configuration สำหรับ Tailscale mesh

#!/usr/bin/env python3
# tailscale_security.py — Security Configuration
import json
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("security")

class TailscaleSecurity:
    def __init__(self):
        self.policies = {}
    
    def full_acl_policy(self):
        """Complete ACL policy for edge computing"""
        return {
            "groups": {
                "group:admins": ["admin@company.com"],
                "group:devops": ["devops@company.com", "sre@company.com"],
                "group:developers": ["dev@company.com"],
            },
            "tagOwners": {
                "tag:cloud": ["group:devops"],
                "tag:edge": ["group:devops"],
                "tag:monitoring": ["group:devops"],
                "tag:admin": ["group:admins"],
            },
            "acls": [
                {"action": "accept", "src": ["tag:admin"], "dst": ["*:*"]},
                {"action": "accept", "src": ["tag:edge"], "dst": ["tag:cloud:443,8080,5432"]},
                {"action": "accept", "src": ["tag:cloud"], "dst": ["tag:edge:22,8080,9100"]},
                {"action": "accept", "src": ["tag:monitoring"], "dst": ["*:9090,9100"]},
                {"action": "accept", "src": ["group:developers"], "dst": ["tag:cloud:8080"]},
            ],
            "ssh": [
                {"action": "accept", "src": ["group:admins"], "dst": ["tag:edge"], "users": ["root", "ubuntu"]},
                {"action": "accept", "src": ["group:devops"], "dst": ["tag:edge"], "users": ["ubuntu"]},
            ],
            "nodeAttrs": [
                {"target": ["tag:edge"], "attr": ["funnel:deny"]},
                {"target": ["tag:cloud"], "attr": ["funnel:deny"]},
            ],
        }
    
    def security_checklist(self):
        return {
            "network": [
                "Enable MFA on Tailscale admin",
                "Use SSO provider (Google/Microsoft/Okta)",
                "Define ACLs (deny by default)",
                "Use tags for device categorization",
                "Enable key expiry",
                "Use ephemeral nodes for temporary access",
            ],
            "edge_nodes": [
                "Use auth keys with tags (not interactive login)",
                "Enable automatic updates",
                "Restrict advertised routes to minimum needed",
                "Monitor node health and connectivity",
                "Rotate auth keys periodically",
                "Use Tailscale SSH instead of exposing port 22",
            ],
            "data": [
                "All traffic encrypted (WireGuard)",
                "No data through relay (DERP) for sensitive data",
                "Enable audit logs",
                "Monitor for unusual access patterns",
            ],
        }

security = TailscaleSecurity()
policy = security.full_acl_policy()
print("ACLs:", json.dumps(policy["acls"], indent=2))

checklist = security.security_checklist()
print("\nChecklist:", json.dumps(checklist["network"], indent=2))

Monitoring และ Troubleshooting

Monitor Tailscale mesh network

# === Monitoring and Troubleshooting ===

# 1. Tailscale Status Commands
# ===================================
# List all nodes and their status:
tailscale status

# Detailed node info:
tailscale status --json | python3 -m json.tool

# Check connectivity to specific node:
tailscale ping edge-bkk-01

# Network diagnostics:
tailscale netcheck

# Debug connection:
tailscale debug derp-map
tailscale debug portmap

# 2. Prometheus Metrics
# ===================================
# Tailscale exposes metrics at localhost:9100 (node-exporter)
# Custom metrics for mesh health:
#
# tailscale_peer_connected (gauge)
# tailscale_peer_latency_seconds (histogram)
# tailscale_bytes_sent_total (counter)
# tailscale_bytes_received_total (counter)
#
# Prometheus scrape config:
# scrape_configs:
#   - job_name: 'tailscale-nodes'
#     static_configs:
#       - targets:
#           - 'edge-bkk-01:9100'
#           - 'edge-cnx-01:9100'
#           - 'edge-hdy-01:9100'

# 3. Grafana Dashboard
# ===================================
# Key panels:
# - Node online/offline status
# - Peer-to-peer latency heatmap
# - Bandwidth per node
# - Connection type (direct vs DERP relay)
# - ACL deny events
# - Auth key expiry countdown

# 4. Common Issues
# ===================================
# Issue: Node shows as "offline"
# Fix: Check tailscaled service, restart if needed
# sudo systemctl restart tailscaled

# Issue: High latency (using DERP relay)
# Fix: Check firewall allows UDP/41641
# Verify with: tailscale netcheck

# Issue: Cannot reach subnet route
# Fix: Verify route is advertised and approved
# tailscale status --json | jq '.Peer[].AllowedIPs'

# Issue: DNS not resolving MagicDNS names
# Fix: Check /etc/resolv.conf points to 100.100.100.100
# Or use: tailscale up --accept-dns=true

# 5. Alerting Rules
# ===================================
# Alert: Node offline > 5 minutes
# Alert: Latency > 200ms between edge and cloud
# Alert: DERP relay usage (should be direct)
# Alert: Auth key expiring in < 7 days
# Alert: Unusual traffic volume from edge node

echo "Monitoring configured"

FAQ คำถามที่พบบ่อย

Q: Tailscale กับ WireGuard ตรงๆ ต่างกันอย่างไร?

A: WireGuard เป็น VPN protocol ที่เร็วและปลอดภัย แต่ต้อง configure เอง ต้อง manage keys, endpoints, firewall rules, NAT traversal เหมาะสำหรับ site-to-site VPN ที่มี static IPs Tailscale สร้างบน WireGuard แต่เพิ่ม coordination layer ที่จัดการ key exchange, NAT traversal, DNS, ACLs ให้อัตโนมัติ ติดตั้งง่าย ใช้ได้ทันที ไม่ต้อง manage infrastructure สำหรับ 2-3 nodes ใช้ WireGuard ตรงได้ สำหรับ 10+ nodes หรือ dynamic environment แนะนำ Tailscale

Q: Tailscale Free Plan เพียงพอไหม?

A: Free Plan (Personal) ให้ 100 devices, 3 users เพียงพอสำหรับ personal use และ small projects ได้ MagicDNS, HTTPS, Tailscale SSH ข้อจำกัด ACLs จำกัด, ไม่มี SSO, ไม่มี audit logs Starter Plan ($5/user/month) เพิ่ม ACLs, SSO, audit logs เหมาะสำหรับทีมเล็ก Business Plan สำหรับ enterprise สำหรับ edge computing ถ้ามี 3-5 edge nodes + ทีม 1-2 คน Free Plan เพียงพอ ถ้ามากกว่านั้นต้อง Starter ขึ้นไป

Q: Tailscale ปลอดภัยไหม?

A: ปลอดภัยมาก ใช้ WireGuard encryption (ChaCha20, Poly1305, Curve25519) traffic เข้ารหัส end-to-end peer-to-peer ไม่ผ่าน Tailscale servers (ยกเว้น DERP relay เมื่อ direct connection ไม่ได้ ซึ่ง encrypted อยู่แล้ว) Tailscale servers เห็นแค่ metadata (ใครเชื่อมต่อกับใคร) ไม่เห็น content ACLs ให้ควบคุม access ละเอียด audit logs ติดตามการใช้งาน SOC 2 Type II certified

Q: Edge computing ทำไมต้องใช้ VPN?

A: Edge devices กระจายอยู่หลายที่ (ร้านค้า, โรงงาน, สาขา) แต่ละที่มี network ต่างกัน อยู่หลัง NAT/firewall ไม่มี public IP ถ้าไม่ใช้ VPN ต้อง expose services ให้ public internet (เสี่ยง) หรือ configure VPN แบบ traditional (ซับซ้อน) Tailscale แก้ปัญหาเหล่านี้ ทำให้ edge devices เข้าถึงได้เหมือนอยู่ใน LAN เดียวกัน deploy updates, collect data, monitor ได้ง่าย โดยไม่ expose ports ให้ public internet

📖 บทความที่เกี่ยวข้อง

Tailscale Mesh Business Continuityอ่านบทความ → Tailscale Mesh Architecture Design Patternอ่านบทความ → Mintlify Docs Edge Computingอ่านบทความ → Tailscale Mesh Home Lab Setupอ่านบทความ → Tailscale Mesh Schema Evolutionอ่านบทความ →

📚 ดูบทความทั้งหมด →