SiamCafe.net Blog
Cybersecurity

Uptime Kuma Monitoring Infrastructure as Code

uptime kuma monitoring infrastructure as code
Uptime Kuma Monitoring Infrastructure as Code | SiamCafe Blog
2025-09-14· อ. บอม — SiamCafe.net· 9,164 คำ

Uptime Kuma Monitoring IaC

Uptime Kuma Open Source Self-hosted Monitoring Uptime HTTP TCP DNS Docker Infrastructure as Code Terraform Ansible Pulumi Git Version Control Automate

Toolประเภทจุดเด่นใช้เมื่อ
Uptime KumaUptime MonitorSelf-hosted ง่าย ฟรีตรวจสอบ Website/API
TerraformIaC ProvisioningMulti-cloud HCLสร้าง Infrastructure
AnsibleConfig ManagementAgentless SSHติดตั้ง Config Software
PrometheusMetrics CollectionTime-series Pullเก็บ Metrics ระบบ
GrafanaVisualizationDashboard Alertsแสดงผล Metrics

Uptime Kuma Setup

# === Uptime Kuma Installation ===

# Docker (แนะนำ)
# docker run -d --restart=always \
#   -p 3001:3001 \
#   -v uptime-kuma:/app/data \
#   --name uptime-kuma \
#   louislam/uptime-kuma:1

# Docker Compose
# version: '3.8'
# services:
#   uptime-kuma:
#     image: louislam/uptime-kuma:1
#     container_name: uptime-kuma
#     restart: always
#     ports:
#       - "3001:3001"
#     volumes:
#       - uptime-kuma-data:/app/data
#     environment:
#       - TZ=Asia/Bangkok
#
# volumes:
#   uptime-kuma-data:

# Reverse Proxy (Nginx)
# server {
#     listen 443 ssl;
#     server_name status.example.com;
#
#     ssl_certificate /etc/letsencrypt/live/status.example.com/fullchain.pem;
#     ssl_certificate_key /etc/letsencrypt/live/status.example.com/privkey.pem;
#
#     location / {
#         proxy_pass http://localhost:3001;
#         proxy_http_version 1.1;
#         proxy_set_header Upgrade $http_upgrade;
#         proxy_set_header Connection "upgrade";
#         proxy_set_header Host $host;
#         proxy_set_header X-Real-IP $remote_addr;
#     }
# }

from dataclasses import dataclass, field
from typing import List

@dataclass
class Monitor:
    name: str
    type: str
    url: str
    interval_sec: int
    retries: int
    status: str
    uptime_30d: float
    avg_response_ms: float

monitors = [
    Monitor("Main Website", "HTTPS", "https://example.com", 60, 3, "UP", 99.95, 245),
    Monitor("API Server", "HTTPS", "https://api.example.com/health", 30, 2, "UP", 99.98, 120),
    Monitor("Database", "TCP", "db.internal:5432", 60, 3, "UP", 99.99, 5),
    Monitor("Redis Cache", "TCP", "redis.internal:6379", 30, 2, "UP", 100.0, 2),
    Monitor("DNS", "DNS", "example.com", 300, 3, "UP", 99.99, 15),
    Monitor("SMTP", "TCP", "mail.example.com:587", 300, 3, "DOWN", 98.50, 0),
]

print("=== Uptime Kuma Monitors ===")
for m in monitors:
    icon = "UP" if m.status == "UP" else "DOWN"
    print(f"  [{icon}] {m.name} ({m.type})")
    print(f"    URL: {m.url}")
    print(f"    Uptime: {m.uptime_30d}% | Response: {m.avg_response_ms}ms | "
          f"Check: {m.interval_sec}s")

Infrastructure as Code

# === Terraform + Ansible for Monitoring Stack ===

# main.tf — Terraform Configuration
# provider "aws" {
#   region = "ap-southeast-1"
# }
#
# resource "aws_instance" "monitoring" {
#   ami           = "ami-0c55b159cbfafe1f0"
#   instance_type = "t3.small"
#   key_name      = "monitoring-key"
#
#   vpc_security_group_ids = [aws_security_group.monitoring.id]
#
#   tags = {
#     Name = "monitoring-server"
#     Role = "uptime-kuma"
#   }
#
#   user_data = <<-EOF
#     #!/bin/bash
#     apt-get update
#     apt-get install -y docker.io docker-compose
#     systemctl enable docker
#     systemctl start docker
#   EOF
# }
#
# resource "aws_security_group" "monitoring" {
#   name = "monitoring-sg"
#
#   ingress {
#     from_port   = 443
#     to_port     = 443
#     protocol    = "tcp"
#     cidr_blocks = ["0.0.0.0/0"]
#   }
#
#   ingress {
#     from_port   = 22
#     to_port     = 22
#     protocol    = "tcp"
#     cidr_blocks = ["10.0.0.0/8"]
#   }
#
#   egress {
#     from_port   = 0
#     to_port     = 0
#     protocol    = "-1"
#     cidr_blocks = ["0.0.0.0/0"]
#   }
# }
#
# output "monitoring_ip" {
#   value = aws_instance.monitoring.public_ip
# }

# Ansible Playbook — deploy-monitoring.yml
# ---
# - hosts: monitoring
#   become: yes
#   tasks:
#     - name: Install Docker
#       apt:
#         name: [docker.io, docker-compose]
#         state: present
#
#     - name: Create Uptime Kuma directory
#       file:
#         path: /opt/uptime-kuma
#         state: directory
#
#     - name: Deploy docker-compose
#       template:
#         src: docker-compose.yml.j2
#         dest: /opt/uptime-kuma/docker-compose.yml
#
#     - name: Start Uptime Kuma
#       community.docker.docker_compose:
#         project_src: /opt/uptime-kuma
#         state: present
#
#     - name: Deploy Nginx config
#       template:
#         src: nginx-monitoring.conf.j2
#         dest: /etc/nginx/sites-available/monitoring
#       notify: reload nginx

iac_tools = {
    "Terraform": {
        "type": "Provisioning",
        "language": "HCL",
        "state": "State File (S3, Terraform Cloud)",
        "use": "สร้าง VM, Network, DB, Load Balancer",
    },
    "Ansible": {
        "type": "Configuration",
        "language": "YAML Playbooks",
        "state": "Stateless (Idempotent)",
        "use": "ติดตั้ง Software, Config, Deploy",
    },
    "Pulumi": {
        "type": "Provisioning",
        "language": "Python, TypeScript, Go",
        "state": "Pulumi Cloud / S3",
        "use": "สร้าง Infrastructure ด้วย Programming Language",
    },
}

print("\nIaC Tools Comparison:")
for tool, info in iac_tools.items():
    print(f"\n  [{tool}]")
    for k, v in info.items():
        print(f"    {k}: {v}")

Notification และ Status Page

# === Notification & Status Page ===

notifications = {
    "Telegram": {"setup": "Bot Token + Chat ID", "speed": "Instant", "cost": "Free"},
    "Slack": {"setup": "Webhook URL", "speed": "Instant", "cost": "Free"},
    "Discord": {"setup": "Webhook URL", "speed": "Instant", "cost": "Free"},
    "Email": {"setup": "SMTP Server", "speed": "1-5 min", "cost": "Free"},
    "PagerDuty": {"setup": "Integration Key", "speed": "Instant", "cost": "Paid"},
    "Line Notify": {"setup": "Access Token", "speed": "Instant", "cost": "Free"},
}

print("Notification Channels:")
for channel, info in notifications.items():
    print(f"  [{channel}] Setup: {info['setup']} | "
          f"Speed: {info['speed']} | Cost: {info['cost']}")

# Status Page Config
status_page = {
    "Public URL": "https://status.example.com",
    "Components": [
        "Website — Main website availability",
        "API — REST API endpoints",
        "Database — Database connectivity",
        "CDN — Content delivery",
        "Email — Email service",
    ],
    "Features": [
        "Public/Private Status Page",
        "Custom Domain",
        "Incident History",
        "Maintenance Window",
        "Custom CSS Branding",
    ],
}

print(f"\n\nStatus Page:")
print(f"  URL: {status_page['Public URL']}")
print(f"\n  Components:")
for comp in status_page['Components']:
    print(f"    - {comp}")
print(f"\n  Features:")
for feat in status_page['Features']:
    print(f"    - {feat}")

# Monitoring Best Practices
practices = [
    "Monitor จาก Multiple Locations ลด False Positive",
    "ตั้ง Alert Threshold เหมาะสม ไม่แจ้งบ่อยเกิน",
    "ใช้ Retry 2-3 ครั้งก่อนแจ้งเตือน",
    "แยก Critical กับ Warning Alerts",
    "ตรวจสอบ SSL Certificate Expiry",
    "Monitor Response Time ไม่ใช่แค่ Up/Down",
    "เก็บ History อย่างน้อย 90 วัน",
]

print(f"\n\nMonitoring Best Practices:")
for i, p in enumerate(practices, 1):
    print(f"  {i}. {p}")

เคล็ดลับ

Best Practices สำหรับนักพัฒนา

การเขียนโค้ดที่ดีไม่ใช่แค่ทำให้โปรแกรมทำงานได้ แต่ต้องเขียนให้อ่านง่าย ดูแลรักษาง่าย และ Scale ได้ หลัก SOLID Principles เป็นพื้นฐานสำคัญที่นักพัฒนาทุกู้คืนควรเข้าใจ ได้แก่ Single Responsibility ที่แต่ละ Class ทำหน้าที่เดียว Open-Closed ที่เปิดให้ขยายแต่ปิดการแก้ไข Liskov Substitution ที่ Subclass ต้องใช้แทน Parent ได้ Interface Segregation ที่แยก Interface ให้เล็ก และ Dependency Inversion ที่พึ่งพา Abstraction ไม่ใช่ Implementation

เรื่อง Testing ก็ขาดไม่ได้ ควรเขียน Unit Test ครอบคลุมอย่างน้อย 80% ของ Code Base ใช้ Integration Test ทดสอบการทำงานร่วมกันของ Module ต่างๆ และ E2E Test สำหรับ Critical User Flow เครื่องมือยอดนิยมเช่น Jest, Pytest, JUnit ช่วยให้การเขียน Test เป็นเรื่องง่าย

เรื่อง Version Control ด้วย Git ใช้ Branch Strategy ที่เหมาะกับทีม เช่น Git Flow สำหรับโปรเจคใหญ่ หรือ Trunk-Based Development สำหรับทีมที่ Deploy บ่อย ทำ Code Review ทุก Pull Request และใช้ CI/CD Pipeline ทำ Automated Testing และ Deployment

เปรียบเทียบข้อดีและข้อเสีย

ข้อดีข้อเสีย
ประสิทธิภาพสูง ทำงานได้เร็วและแม่นยำ ลดเวลาทำงานซ้ำซ้อนต้องใช้เวลาเรียนรู้เบื้องต้นพอสมควร มี Learning Curve สูง
มี Community ขนาดใหญ่ มีคนช่วยเหลือและแหล่งเรียนรู้มากมายบางฟีเจอร์อาจยังไม่เสถียร หรือมีการเปลี่ยนแปลงบ่อยในเวอร์ชันใหม่
รองรับ Integration กับเครื่องมือและบริการอื่นได้หลากหลายต้นทุนอาจสูงสำหรับ Enterprise License หรือ Cloud Service
เป็น Open Source หรือมีเวอร์ชันฟรีให้เริ่มต้นใช้งานต้องการ Hardware หรือ Infrastructure ที่เพียงพอ

จากตารางเปรียบเทียบจะเห็นว่าข้อดีมีมากกว่าข้อเสียอย่างชัดเจน โดยเฉพาะในแง่ของประสิทธิภาพและความสามารถในการ Scale สำหรับข้อเสียส่วนใหญ่สามารถแก้ไขได้ด้วยการเรียนรู้อย่างเป็นระบบและวางแผนทรัพยากรให้เหมาะสม

Uptime Kuma คืออะไร

Open Source Self-hosted Monitoring HTTP TCP DNS Docker UI สวย Telegram Slack Discord Alert ฟรี ติดตั้งง่าย

Infrastructure as Code (IaC) คืออะไร

จัดการ Infrastructure ด้วย Code Terraform Ansible Pulumi Git Version Control ทำซ้ำ ตรวจสอบ Review Automate

Uptime Kuma กับ Grafana ต่างกันอย่างไร

Uptime Kuma Uptime Monitor ง่าย Up/Down Grafana Visualization Prometheus ซับซ้อน ยืดหยุ่น Dashboard ใช้ร่วมกันได้

Terraform กับ Ansible ต่างกันอย่างไร

Terraform Provisioning สร้าง Infrastructure HCL State Ansible Configuration ติดตั้ง Software YAML SSH Agentless ใช้ร่วมกัน

สรุป

Uptime Kuma Self-hosted Monitoring HTTP TCP DNS Docker Infrastructure as Code Terraform Ansible Pulumi Notification Telegram Slack Status Page GitOps Version Control Automate

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

Uptime Kuma Monitoring Edge Deploymentอ่านบทความ → Uptime Kuma Monitoring Disaster Recovery Planอ่านบทความ → Uptime Kuma Monitoring Pub Sub Architectureอ่านบทความ → Uptime Kuma Monitoring Stream Processingอ่านบทความ →

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