ฐานข้อมูลเป็นหัวใจสำคัญของทุกระบบ การ สำรองข้อมูล (Backup) และ กู้คืนข้อมูล (Restore) จึงเป็นสิ่งที่ DBA และนักพัฒนาต้องให้ความสำคัญ PostgreSQL มีเครื่องมือในตัวอย่าง pg_dump
และ pg_restore
ที่ช่วยให้กระบวนการนี้ง่ายและมีประสิทธิภาพ บทความนี้จะอธิบายการใช้งานแบบละเอียด
pg_dump คืออะไร?
pg_dump
คือเครื่องมือที่ใช้ในการสำรองข้อมูลฐานข้อมูล PostgreSQL โดยสามารถสำรองได้ทั้งแบบ Plain SQL Script หรือแบบ Binary Format
# Backup แบบ Plain SQL pg_dump -U postgres mydb > mydb.sql # Backup แบบ Custom Format (ใช้กับ pg_restore) pg_dump -U postgres -Fc mydb > mydb.dump
pg_restore คืออะไร?
pg_restore
ใช้สำหรับกู้คืนข้อมูลจากไฟล์ที่สร้างด้วย pg_dump -Fc
สามารถเลือก Restore เฉพาะ Table หรือ Schema ได้
# Restore ข้อมูลทั้งหมด pg_restore -U postgres -d newdb mydb.dump # Restore แบบเพิ่มตาราง pg_restore -U postgres -d newdb -t users mydb.dump
การ Backup ฐานข้อมูลทั้ง Cluster
หากต้องการ Backup ฐานข้อมูลทุกตัวใน Cluster สามารถใช้ pg_dumpall
pg_dumpall -U postgres > all_databases.sql
การ Restore จาก Plain SQL
หาก Backup เป็น Plain SQL สามารถ Restore ได้ด้วย psql
psql -U postgres -d newdb < mydb.sql
การเลือก Option ที่เหมาะสม
-Fc
→ ใช้ Custom Format (เหมาะกับการ Restore ที่ยืดหยุ่น)-j
→ ใช้ Parallel Jobs (เพิ่มความเร็ว)-t
→ เลือก Table ที่ต้องการ-n
→ เลือก Schema ที่ต้องการ
pg_dump -U postgres -Fc -j 4 -n public mydb > mydb_parallel.dump
การทดสอบ Backup & Restore
สิ่งสำคัญคืออย่าเพียงแค่ Backup แต่ต้อง ทดสอบการ Restore ด้วย เพื่อมั่นใจว่าไฟล์ Backup ใช้งานได้จริง
# Step 1: Backup pg_dump -U postgres -Fc mydb > mydb.dump # Step 2: สร้าง Database ใหม่ createdb -U postgres test_restore # Step 3: Restore pg_restore -U postgres -d test_restore mydb.dump
Best Practices
- วางแผนตารางเวลาสำรองข้อมูล (Daily, Weekly, Incremental)
- เก็บไฟล์ Backup ไว้หลาย Location (On-premise + Cloud)
- ทดสอบการ Restore อย่างน้อยเดือนละครั้ง
- ใช้ Parallel Dump สำหรับ Database ขนาดใหญ่
- กำหนดสิทธิ์การเข้าถึงไฟล์ Backup อย่างปลอดภัย
สรุป
การสำรองและกู้คืนข้อมูลเป็นสิ่งจำเป็นสำหรับทุกระบบ pg_dump และ pg_restore เป็นเครื่องมือที่มีประสิทธิภาพและใช้งานง่าย หากวางแผนและทดสอบอย่างเหมาะสม จะช่วยป้องกันการสูญหายของข้อมูลและทำให้ระบบมีความมั่นคงปลอดภัย
SEO Keywords
PostgreSQL Backup,Postgres pg_dump,Postgres pg_restore,Database Restore PostgreSQL,Postgres Backup Tools,PostgreSQL Backup Best Practices,pg_dumpall PostgreSQL