SiamCafe.net Blog
Technology

Linkerd Service Mesh Micro-segmentation

linkerd service mesh micro segmentation
Linkerd Service Mesh Micro-segmentation | SiamCafe Blog
2026-01-27· อ. บอม — SiamCafe.net· 1,258 คำ

Linkerd Service Mesh Micro-segmentation คืออะไร

Linkerd เป็น lightweight service mesh สำหรับ Kubernetes สร้างโดย Buoyant เขียนด้วย Rust ทำให้ใช้ resources น้อยมาก (~20MB RAM per proxy) Micro-segmentation คือการแบ่ง network ออกเป็น segments เล็กๆ เพื่อจำกัดการเข้าถึงระหว่าง services ตามหลัก Zero Trust — ทุก service ต้องพิสูจน์ตัวตนและได้รับอนุญาตก่อนสื่อสารกัน Linkerd ใช้ mTLS อัตโนมัติและ Server Authorization Policies เพื่อ enforce micro-segmentation โดยไม่ต้องเปลี่ยน application code

Linkerd Architecture

# linkerd_arch.py — Linkerd service mesh architecture
import json

class LinkerdArchitecture:
    COMPONENTS = {
        "control_plane": {
            "name": "Control Plane",
            "sub_components": {
                "destination": "Destination controller — service discovery + routing policies",
                "identity": "Identity controller — ออก TLS certificates (mTLS)",
                "proxy_injector": "Proxy Injector — inject sidecar proxy อัตโนมัติ",
            },
        },
        "data_plane": {
            "name": "Data Plane (linkerd2-proxy)",
            "description": "Ultra-lightweight proxy เขียนด้วย Rust — ~20MB RAM, < 1ms latency",
            "features": ["mTLS automatic", "Load balancing (EWMA)", "Retries + timeouts", "Metrics (Prometheus)"],
        },
        "viz": {
            "name": "Linkerd Viz (Dashboard)",
            "description": "Web dashboard + CLI — ดู traffic, success rate, latency, topology",
        },
    }

    VS_ISTIO = {
        "linkerd": {
            "proxy": "linkerd2-proxy (Rust, ~20MB)",
            "complexity": "Simple — minimal config",
            "performance": "< 1ms latency overhead",
            "features": "mTLS, observability, retries, policy",
        },
        "istio": {
            "proxy": "Envoy (C++, ~100MB)",
            "complexity": "Complex — many CRDs",
            "performance": "2-5ms latency overhead",
            "features": "mTLS, traffic management, fault injection, rate limiting",
        },
    }

    def show_components(self):
        print("=== Linkerd Architecture ===\n")
        for key, comp in self.COMPONENTS.items():
            print(f"[{comp['name']}]")
            if 'sub_components' in comp:
                for sub, desc in comp['sub_components'].items():
                    print(f"  • {sub}: {desc}")
            if 'description' in comp:
                print(f"  {comp['description']}")
            print()

    def show_comparison(self):
        print("=== Linkerd vs Istio ===")
        print(f"  {'Feature':<15} {'Linkerd':<35} {'Istio'}")
        for feat in ['proxy', 'complexity', 'performance']:
            print(f"  {feat:<15} {self.VS_ISTIO['linkerd'][feat]:<35} {self.VS_ISTIO['istio'][feat]}")

arch = LinkerdArchitecture()
arch.show_components()
arch.show_comparison()

Micro-segmentation with Authorization Policies

# microseg.py — Linkerd micro-segmentation policies
import json

class MicroSegmentation:
    POLICIES = """
# === Linkerd Server Authorization Policies ===

# 1. Default deny — ปฏิเสธ traffic ทั้งหมดที่ไม่มี policy
apiVersion: policy.linkerd.io/v1beta2
kind: Server
metadata:
  name: payment-api
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payment-api
  port: 8080
  proxyProtocol: HTTP/2
---
# 2. อนุญาตเฉพาะ order-service เข้าถึง payment-api
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata:
  name: allow-orders-to-payments
  namespace: payments
spec:
  targetRef:
    group: policy.linkerd.io
    kind: Server
    name: payment-api
  requiredAuthenticationRefs:
    - name: orders-identity
      kind: MeshTLSAuthentication
      group: policy.linkerd.io
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata:
  name: orders-identity
  namespace: payments
spec:
  identities:
    - "order-service.orders.serviceaccount.identity.linkerd.cluster.local"
---
# 3. อนุญาต frontend เข้าถึง order-service
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata:
  name: allow-frontend-to-orders
  namespace: orders
spec:
  targetRef:
    group: policy.linkerd.io
    kind: Server
    name: order-api
  requiredAuthenticationRefs:
    - name: frontend-identity
      kind: MeshTLSAuthentication
      group: policy.linkerd.io
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata:
  name: frontend-identity
  namespace: orders
spec:
  identities:
    - "frontend.web.serviceaccount.identity.linkerd.cluster.local"
"""

    ZERO_TRUST = [
        "Default Deny — ทุก traffic ถูกปฏิเสธ ถ้าไม่มี AuthorizationPolicy",
        "Identity-based — อนุญาตตาม service identity (mTLS cert) ไม่ใช่ IP",
        "Least Privilege — แต่ละ service เข้าถึงเฉพาะ services ที่จำเป็น",
        "Encryption — mTLS ทุก connection อัตโนมัติ",
        "Audit — ดู traffic flow ผ่าน Linkerd Viz dashboard",
    ]

    def show_policies(self):
        print("=== Authorization Policies ===")
        print(self.POLICIES[:600])

    def show_zero_trust(self):
        print("\n=== Zero Trust Principles ===")
        for zt in self.ZERO_TRUST:
            print(f"  • {zt}")

seg = MicroSegmentation()
seg.show_policies()
seg.show_zero_trust()

Python Policy Generator

# policy_gen.py — Generate Linkerd policies from service map
import json

class PolicyGenerator:
    CODE = """
# linkerd_policy_gen.py — Generate micro-segmentation policies
import yaml
import json
from typing import Dict, List

class LinkerdPolicyGenerator:
    def __init__(self, cluster_domain="cluster.local"):
        self.cluster_domain = cluster_domain
        self.policies = []
    
    def service_identity(self, service_account, namespace):
        '''Generate Linkerd identity string'''
        return f"{service_account}.{namespace}.serviceaccount.identity.linkerd.{self.cluster_domain}"
    
    def create_server(self, name, namespace, app_label, port, protocol="HTTP/2"):
        '''Create Server resource'''
        return {
            "apiVersion": "policy.linkerd.io/v1beta2",
            "kind": "Server",
            "metadata": {"name": name, "namespace": namespace},
            "spec": {
                "podSelector": {"matchLabels": {"app": app_label}},
                "port": port,
                "proxyProtocol": protocol,
            },
        }
    
    def create_auth_policy(self, name, namespace, server_name, allowed_identities):
        '''Create AuthorizationPolicy'''
        auth_name = f"{name}-auth"
        
        # MeshTLSAuthentication
        mesh_auth = {
            "apiVersion": "policy.linkerd.io/v1alpha1",
            "kind": "MeshTLSAuthentication",
            "metadata": {"name": auth_name, "namespace": namespace},
            "spec": {"identities": allowed_identities},
        }
        
        # AuthorizationPolicy
        policy = {
            "apiVersion": "policy.linkerd.io/v1alpha1",
            "kind": "AuthorizationPolicy",
            "metadata": {"name": name, "namespace": namespace},
            "spec": {
                "targetRef": {
                    "group": "policy.linkerd.io",
                    "kind": "Server",
                    "name": server_name,
                },
                "requiredAuthenticationRefs": [{
                    "name": auth_name,
                    "kind": "MeshTLSAuthentication",
                    "group": "policy.linkerd.io",
                }],
            },
        }
        
        self.policies.extend([mesh_auth, policy])
        return policy
    
    def generate_from_service_map(self, service_map: Dict[str, Dict]):
        '''Generate policies from service dependency map'''
        all_resources = []
        
        for service, config in service_map.items():
            ns = config['namespace']
            port = config['port']
            
            # Create Server
            server = self.create_server(
                name=f"{service}-server",
                namespace=ns,
                app_label=service,
                port=port,
            )
            all_resources.append(server)
            
            # Create policies for allowed callers
            if 'allowed_from' in config:
                identities = [
                    self.service_identity(caller['sa'], caller['ns'])
                    for caller in config['allowed_from']
                ]
                
                self.create_auth_policy(
                    name=f"allow-to-{service}",
                    namespace=ns,
                    server_name=f"{service}-server",
                    allowed_identities=identities,
                )
        
        all_resources.extend(self.policies)
        return all_resources
    
    def export_yaml(self, resources, output_file="policies.yaml"):
        '''Export policies as YAML'''
        with open(output_file, 'w') as f:
            yaml.dump_all(resources, f, default_flow_style=False)
        return output_file

# Example service map
service_map = {
    "payment-api": {
        "namespace": "payments",
        "port": 8080,
        "allowed_from": [
            {"sa": "order-service", "ns": "orders"},
        ],
    },
    "order-api": {
        "namespace": "orders",
        "port": 8080,
        "allowed_from": [
            {"sa": "frontend", "ns": "web"},
            {"sa": "admin-api", "ns": "admin"},
        ],
    },
}

# gen = LinkerdPolicyGenerator()
# resources = gen.generate_from_service_map(service_map)
# gen.export_yaml(resources, "linkerd-policies.yaml")
"""

    def show_code(self):
        print("=== Policy Generator ===")
        print(self.CODE[:600])

gen = PolicyGenerator()
gen.show_code()

Installation & Setup

# setup.py — Linkerd installation and setup
import json

class LinkerdSetup:
    INSTALL = """
# === Linkerd Installation ===

# 1. Install CLI
curl --proto '=https' --tlsv1.2 -sSfL https://run.linkerd.io/install | sh
export PATH=$HOME/.linkerd2/bin:$PATH

# 2. Pre-check
linkerd check --pre

# 3. Install CRDs
linkerd install --crds | kubectl apply -f -

# 4. Install Control Plane
linkerd install | kubectl apply -f -

# 5. Verify
linkerd check

# 6. Install Viz (dashboard)
linkerd viz install | kubectl apply -f -
linkerd viz dashboard &

# 7. Inject sidecar to namespace
kubectl annotate namespace my-app linkerd.io/inject=enabled

# 8. Restart pods to inject proxy
kubectl rollout restart deployment -n my-app

# 9. Verify mesh
linkerd viz stat deploy -n my-app
"""

    VERIFY_COMMANDS = """
# === Verification Commands ===

# Check mesh status
linkerd check

# View live traffic
linkerd viz top deploy/payment-api -n payments

# View routes
linkerd viz routes deploy/payment-api -n payments

# Check mTLS status
linkerd viz edges deploy -n payments

# View authorization policy status
linkerd viz authz deploy/payment-api -n payments

# Dashboard
linkerd viz dashboard
"""

    def show_install(self):
        print("=== Installation ===")
        print(self.INSTALL[:500])

    def show_verify(self):
        print("\n=== Verification ===")
        print(self.VERIFY_COMMANDS[:400])

setup = LinkerdSetup()
setup.show_install()
setup.show_verify()

Monitoring & Troubleshooting

# monitoring.py — Linkerd monitoring
import json
import random

class LinkerdMonitoring:
    METRICS = {
        "success_rate": "Request success rate per service — ควร > 99.9%",
        "latency_p99": "P99 latency — ควร < SLO target",
        "request_volume": "Requests per second per service",
        "tcp_connections": "Active TCP connections between services",
        "tls_status": "mTLS status — ทุก connection ควรเป็น secured",
        "policy_denials": "Authorization policy denials — unauthorized access attempts",
    }

    PROMETHEUS_QUERIES = """
# Success rate per deployment
sum(rate(response_total{classification="success"}[5m])) by (deployment)
/
sum(rate(response_total[5m])) by (deployment)

# P99 latency
histogram_quantile(0.99,
  sum(rate(response_latency_ms_bucket[5m])) by (le, deployment)
)

# Policy denials
sum(rate(inbound_http_authz_deny_total[5m])) by (deployment)
"""

    TROUBLESHOOTING = {
        "mtls_not_working": {
            "symptom": "Edges show 'not secured'",
            "fix": "ตรวจสอบ linkerd.io/inject annotation + restart pods",
        },
        "policy_deny_all": {
            "symptom": "ทุก request ถูก deny",
            "fix": "ตรวจสอบ Server + AuthorizationPolicy — identity string ต้องถูกต้อง",
        },
        "high_latency": {
            "symptom": "Latency เพิ่มหลังติดตั้ง mesh",
            "fix": "ตรวจสอบ proxy resources, connection pooling, protocol detection",
        },
    }

    def show_metrics(self):
        print("=== Key Metrics ===\n")
        for metric, desc in self.METRICS.items():
            print(f"  [{metric}] {desc}")

    def show_queries(self):
        print(f"\n=== Prometheus Queries ===")
        print(self.PROMETHEUS_QUERIES[:300])

    def show_troubleshooting(self):
        print(f"\n=== Troubleshooting ===")
        for key, issue in self.TROUBLESHOOTING.items():
            print(f"  [{issue['symptom']}]")
            print(f"    Fix: {issue['fix']}")

    def sample_dashboard(self):
        print(f"\n=== Service Dashboard ===")
        services = [
            {"name": "frontend", "sr": f"{random.uniform(99.5,100):.2f}%", "p99": f"{random.randint(5,30)}ms", "rps": random.randint(50,500)},
            {"name": "order-api", "sr": f"{random.uniform(99.0,100):.2f}%", "p99": f"{random.randint(10,50)}ms", "rps": random.randint(20,200)},
            {"name": "payment-api", "sr": f"{random.uniform(99.5,100):.2f}%", "p99": f"{random.randint(15,80)}ms", "rps": random.randint(10,100)},
        ]
        print(f"  {'Service':<15} {'Success Rate':<14} {'P99 Latency':<13} {'RPS'}")
        for s in services:
            print(f"  {s['name']:<15} {s['sr']:<14} {s['p99']:<13} {s['rps']}")

mon = LinkerdMonitoring()
mon.show_metrics()
mon.show_troubleshooting()
mon.sample_dashboard()

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

Q: Linkerd กับ Istio อันไหนดีกว่าสำหรับ micro-segmentation?

A: Linkerd: ง่ายกว่า, เร็วกว่า, resources น้อยกว่า — เหมาะสำหรับทีมที่ต้องการ security + observability โดยไม่ซับซ้อน Istio: features มากกว่า (traffic management, fault injection, rate limiting) — เหมาะสำหรับ complex environments Micro-segmentation: ทั้งสองทำได้ — Linkerd ใช้ Server + AuthorizationPolicy, Istio ใช้ AuthorizationPolicy เลือก Linkerd: simplicity + performance, เลือก Istio: advanced traffic control

Q: Default deny จำเป็นไหม?

A: จำเป็นมากสำหรับ Zero Trust — ถ้าไม่มี default deny ทุก service คุยกันได้หมด วิธี: สร้าง Server resource สำหรับทุก port ที่ต้อง protect → Linkerd จะ deny traffic ที่ไม่มี AuthorizationPolicy เริ่มจาก: audit mode (log แต่ไม่ deny) → enforce (deny จริง) เมื่อมั่นใจ

Q: Linkerd mTLS ต่างจาก NetworkPolicy อย่างไร?

A: NetworkPolicy: L3/L4 — จำกัดตาม IP, port, namespace (ไม่มี identity, ไม่เข้ารหัส) Linkerd mTLS + AuthorizationPolicy: L7 — จำกัดตาม service identity (certificate), เข้ารหัสทุก connection ใช้ร่วมกัน: NetworkPolicy สำหรับ baseline L3/L4 + Linkerd สำหรับ identity-based L7 security

Q: Performance impact ของ Linkerd เป็นอย่างไร?

A: Latency: < 1ms overhead (P99) — เบาที่สุดในบรรดา service meshes Memory: ~20MB per proxy (vs Envoy ~100MB) CPU: minimal — Rust proxy มี efficiency สูงมาก จากการทดสอบ: Linkerd เพิ่ม latency น้อยที่สุดเมื่อเทียบกับ Istio, Consul Connect สำหรับ high-performance workloads: Linkerd เป็นตัวเลือกที่ดีที่สุด

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

Linkerd Service Mesh Production Setup Guideอ่านบทความ → Flatcar Container Linux Service Mesh Setupอ่านบทความ → Linkerd Service Mesh Serverless Architectureอ่านบทความ → mTLS Service Mesh Machine Learning Pipelineอ่านบทความ → OPA Gatekeeper Service Mesh Setupอ่านบทความ →

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