🌍 Networking

Tailscale

Tailscale

A mesh VPN based on WireGuard for building Zero Trust networks. Optimizes team collaboration with MagicDNS, ACLs, and DERP relays.

📖 Detailed Explanation

Tailscale is a mesh VPN service based on the WireGuard protocol that lets you build a secure team collaboration environment without complex network configuration. Unlike traditional VPNs that route all traffic through a central server, Tailscale builds a P2P (Peer-to-Peer) mesh network that supports direct connections between devices.

The core of Tailscale is its Zero Trust security model. All connections are protected by WireGuard encryption, and fine-grained access control is possible through ACLs (Access Control Lists). It integrates with SSO (Single Sign-On) from Google, Microsoft, GitHub and others, so it can be adopted easily in enterprise environments as well.

MagicDNS is one of Tailscale's powerful features. It automatically assigns a DNS name to every device in the Tailnet, so you can connect with a name like 'macbook.tail12345.ts.net' without having to memorize IP addresses. This ensures a stable connection even in dynamic IP environments.

The DERP (Designated Encrypted Relay for Packets) relay is activated when a direct P2P connection is not possible in a NAT environment. DERP servers distributed around the world relay encrypted traffic, so even devices behind a firewall can connect securely. Once the connection is established, it automatically switches to a direct connection to maintain optimal performance.

💻 Code Example

# Tailscale 설치 (Linux)
curl -fsSL https://tailscale.com/install.sh | sh

# Tailscale 시작 및 인증
sudo tailscale up

# 현재 상태 확인
tailscale status

# 네트워크 내 기기 목록
tailscale status --json | jq '.Peer'

# MagicDNS로 SSH 접속
ssh user@devserver.tail12345.ts.net

# 특정 포트만 노출 (Exit Node)
sudo tailscale up --advertise-exit-node

# ACL 태그 적용
sudo tailscale up --advertise-tags=tag:server

# Tailscale IP 확인
tailscale ip -4  # IPv4 주소
tailscale ip -6  # IPv6 주소

# 연결 상태 디버깅
tailscale netcheck
tailscale ping devserver

# 파일 공유 (Taildrop)
tailscale file cp ./report.pdf user@macbook:

# 연결 해제
sudo tailscale down

# 로그아웃 (인증 해제)
sudo tailscale logout
// Tailscale API를 활용한 기기 관리 (Node.js)
const axios = require('axios');

const TAILSCALE_API_KEY = process.env.TAILSCALE_API_KEY;
const TAILNET = 'your-tailnet.ts.net';

const tailscaleApi = axios.create({
    baseURL: 'https://api.tailscale.com/api/v2',
    headers: {
        'Authorization': `Bearer ${TAILSCALE_API_KEY}`
    }
});

// 모든 기기 목록 조회
async function getDevices() {
    const { data } = await tailscaleApi.get(`/tailnet/${TAILNET}/devices`);
    return data.devices.map(device => ({
        name: device.name,
        addresses: device.addresses,
        os: device.os,
        lastSeen: device.lastSeen,
        online: device.online
    }));
}

// 기기 승인 (관리자 기능)
async function authorizeDevice(deviceId) {
    await tailscaleApi.post(`/device/${deviceId}/authorized`, {
        authorized: true
    });
    console.log(`Device ${deviceId} authorized`);
}

// 기기에 태그 할당
async function setDeviceTags(deviceId, tags) {
    await tailscaleApi.post(`/device/${deviceId}/tags`, {
        tags: tags  // ["tag:server", "tag:production"]
    });
}

// DNS 레코드 조회
async function getDNSRecords() {
    const { data } = await tailscaleApi.get(`/tailnet/${TAILNET}/dns/nameservers`);
    return data;
}

// 사용 예시
(async () => {
    const devices = await getDevices();
    devices.filter(d => d.online).forEach(d => {
        console.log(`${d.name}: ${d.addresses[0]}`);
    });
})();
package main

import (
    "context"
    "fmt"
    "log"
    "net"
    "net/http"

    "tailscale.com/client/tailscale"
    "tailscale.com/tsnet"
)

// tsnet을 사용한 Tailscale 임베디드 서버
func main() {
    // Tailscale 서버 인스턴스 생성
    srv := &tsnet.Server{
        Hostname: "my-app-server",
        AuthKey:  "tskey-auth-xxxxx", // 환경변수 권장
    }
    defer srv.Close()

    // Tailscale 네트워크에서 리스닝
    ln, err := srv.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal(err)
    }
    defer ln.Close()

    // 현재 Tailscale 상태 확인
    lc, err := srv.LocalClient()
    if err != nil {
        log.Fatal(err)
    }

    status, err := lc.Status(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Tailscale IP: %v\n", status.TailscaleIPs)
    fmt.Printf("MagicDNS name: %s\n", status.Self.DNSName)

    // HTTP 서버 실행 (Tailscale 네트워크 전용)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 요청자의 Tailscale 정보 확인
        who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
        if err != nil {
            http.Error(w, "Unauthorized", 401)
            return
        }
        fmt.Fprintf(w, "Hello, %s!\n", who.UserProfile.LoginName)
    })

    log.Printf("Server running on Tailscale network...")
    log.Fatal(http.Serve(ln, nil))
}

🗣️ Say It Like This in Practice

💬 In a discussion on setting up a remote work environment
"Instead of adopting VPN equipment, let's consider Tailscale. Because it's based on WireGuard, it's fast, and since it's configured as a mesh network without a separate server, there's no need to worry about a SPOF (Single Point of Failure). With ACLs, we can segment access so that developers can reach only the development servers and the operations team only production."
💬 In an infrastructure team meeting
"Even for internal servers behind NAT, the DERP relay takes care of connecting them, so there's no need to touch port forwarding or firewall settings. And thanks to MagicDNS, even if the IP changes, you can just connect with 'db-primary.tail12345.ts.net'. The operational burden drops significantly."
💬 When responding to a security audit
"Tailscale follows the Zero Trust model. All traffic is E2E encrypted with WireGuard, and a unique certificate is issued for each device. If you integrate with the corporate IdP via SAML/OIDC, network access is blocked immediately when a departed employee's account is deactivated."

⚠️ Common Mistakes & Cautions

❌
Indiscriminate use of Exit Nodes

When you enable an Exit Node, all internet traffic passes through that device. Considering bandwidth costs and reduced speed, route only specific subnets, or use the --exit-node option only when needed.

❌
Operating without ACL configuration

By default, all devices can access each other. In production environments, be sure to configure ACLs and apply the principle of least privilege, for example, preventing 'tag:dev' devices from accessing 'tag:prod' servers.

❌
Creating a team network with a personal account

If you create a Tailnet with a personal Gmail account, you lose administrative control of the entire network when you leave the company. Be sure to create it with a company domain account or a GitHub Organization.

✅
Recommended settings

Integrate SAML/OIDC SSO, require MFA, enable Key Expiry (90 days recommended), and integrate legacy systems through subnet routers. Integrate Audit Logs with your SIEM to monitor access history.

🔗 Related Terms

📚 Learn More