คู่มือนี้แนะนำวิธีเชื่อมต่อ MySQL Server แบบ Remote อย่างปลอดภัยด้วย SSH Tunnel (Port Forwarding) แทนการเปิด Port 3306 บน Public Internet
ทำไมต้องใช้ SSH Tunnel?
- MySQL Protocol ไม่ได้เข้ารหัสโดยค่าเริ่มต้น (Clear text)
- เปิด Port 3306 สาธารณะ = โจมตี Brute-force, Data breach
- SSH Tunnel = เข้ารหัส end-to-end, ใช้ Key-based auth, ผ่าน Firewall ได้
คำสั่งสร้าง SSH Tunnel
ssh -L 6666:localhost:3306 user@remoteserver.net
อธิบายพารามิเตอร์
| ส่วน | คำอธิบาย |
|---|---|
-L | Local Port Forwarding |
6666 | Local Port บนเครื่อง Client (เลือกได้ ใส่ > 1024) |
localhost:3306 | Destination จากมุมมอง Remote Server (localhost = ตัว server เอง, port 3306 = MySQL) |
user@remoteserver.net | SSH Credentials ของ Remote Server |
| Setting | Value |
|---|---|
| Host | 127.0.0.1 (ต้องใช้ IP ไม่ใช่ localhost) |
| Port | 6666 (Local port ที่ตั้งไว้) |
| Username | MySQL Username |
| Password | MySQL Password |
⚠️ หมายเหตุ: ต้องใช้
127.0.0.1 ไม่ใช่ localhost เพราะ MySQL client ตีความ localhost = Unix socket ไม่ใช่ TCP
ตัวเลือกเพิ่มเติม
# รันในพื้นหลัง (Background)
ssh -f -N -L 6666:localhost:3306 user@remoteserver.net
# -f = background, -N = ไม่รัน remote command
# ใช้ SSH Key แทนรหัสผ่าน
ssh -i ~/.ssh/id_rsa -L 6666:localhost:3306 user@remoteserver.net
# บีบอัดข้อมูล (เร็วขึ้นบนเครือข่ายช้า)
ssh -C -L 6666:localhost:3306 user@remoteserver.net
ปิด Tunnel
กด Ctrl+C ที่ Terminal ที่รัน ssh หรือ kill process
ทางเลือกอื่น
- VPN (WireGuard, OpenVPN, Tailscale) - ปลอดภัยกว่า เข้าถึง network ทั้งหมด
- MySQL SSL/TLS - ใบรับรองบน MySQL เอง (ซับซ้อนกว่า)
- ProxySQL - Load balancer/Proxy สำหรับ MySQL
SSH Tunnel เป็นวิธีที่ง่าย ที่สุดเร็ว และปลอดภัยสำหรับการเข้าถึง MySQL Remote แบบ Ad-hoc