🗄️ Databases

Backup

Backup

The task of creating copies to prepare for data loss. Divided into full, incremental, and differential backups, and a core foundation of disaster recovery.

📖 Detailed Explanation

Full Backup copies all data completely. Restoration is the simplest, but it requires a lot of time and storage space. It is usually performed on a weekly or monthly basis.

Incremental Backup copies only the data changed since the last backup. It takes less backup time and space, but restoration requires applying the full backup plus all incremental backups in sequence. PostgreSQL's WAL archiving is a representative example.

Differential Backup copies all data changed since the last full backup. It is larger than an incremental backup, but restoration only requires the full backup plus the most recent differential backup.

Logical backup vs. physical backup: Logical backups (pg_dump, mysqldump) extract data in SQL form, which makes them highly portable but slow. Physical backups (pg_basebackup, Percona XtraBackup) copy data files directly, which makes them fast but restorable only on the same version.

The 3-2-1 backup rule is an industry-standard best practice: keep at least 3 copies of the data, on 2 different storage media, with 1 stored offsite (cloud, remote location).

💻 Code Example

# 데이터베이스 백업 자동화 - Python
import subprocess
import boto3
from datetime import datetime
from pathlib import Path
import gzip
import os

class DatabaseBackup:
    """PostgreSQL/MySQL 백업 관리 클래스"""

    def __init__(self, db_config: dict, s3_bucket: str = None):
        self.db_config = db_config
        self.s3_bucket = s3_bucket
        self.backup_dir = Path("/var/backups/db")
        self.backup_dir.mkdir(parents=True, exist_ok=True)

    def create_postgresql_backup(self, backup_type: str = "full") -> Path:
        """
        PostgreSQL 백업 생성
        - full: pg_dump로 전체 백업
        - basebackup: pg_basebackup으로 물리적 백업
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        db_name = self.db_config['database']

        if backup_type == "full":
            # 논리적 백업 (SQL 덤프)
            backup_file = self.backup_dir / f"{db_name}_{timestamp}.sql.gz"

            # pg_dump 실행 후 gzip 압축
            dump_cmd = [
                "pg_dump",
                "-h", self.db_config['host'],
                "-p", str(self.db_config.get('port', 5432)),
                "-U", self.db_config['user'],
                "-d", db_name,
                "-F", "p",  # plain SQL format
                "--no-owner",
                "--no-acl"
            ]

            env = os.environ.copy()
            env['PGPASSWORD'] = self.db_config['password']

            with gzip.open(backup_file, 'wt') as f:
                result = subprocess.run(
                    dump_cmd, stdout=f, stderr=subprocess.PIPE,
                    env=env, text=True
                )

            if result.returncode != 0:
                raise Exception(f"Backup failed: {result.stderr}")

            print(f"✅ Full backup created: {backup_file}")

        elif backup_type == "basebackup":
            # 물리적 백업 (PITR 지원)
            backup_file = self.backup_dir / f"{db_name}_base_{timestamp}"

            basebackup_cmd = [
                "pg_basebackup",
                "-h", self.db_config['host'],
                "-p", str(self.db_config.get('port', 5432)),
                "-U", self.db_config['user'],
                "-D", str(backup_file),
                "-Ft",  # tar format
                "-z",   # gzip compression
                "-P"    # progress
            ]

            env = os.environ.copy()
            env['PGPASSWORD'] = self.db_config['password']

            result = subprocess.run(basebackup_cmd, env=env)
            if result.returncode != 0:
                raise Exception("Base backup failed")

            print(f"✅ Base backup created: {backup_file}")

        return backup_file

    def upload_to_s3(self, backup_file: Path, retention_days: int = 30):
        """백업 파일을 S3에 업로드 (3-2-1 규칙의 오프사이트 보관)"""
        if not self.s3_bucket:
            raise ValueError("S3 bucket not configured")

        s3 = boto3.client('s3')
        s3_key = f"backups/{backup_file.name}"

        # 업로드
        s3.upload_file(str(backup_file), self.s3_bucket, s3_key)

        # 수명 주기 태그 설정
        s3.put_object_tagging(
            Bucket=self.s3_bucket,
            Key=s3_key,
            Tagging={'TagSet': [
                {'Key': 'retention-days', 'Value': str(retention_days)}
            ]}
        )

        print(f"✅ Uploaded to S3: s3://{self.s3_bucket}/{s3_key}")

    def cleanup_old_backups(self, retention_days: int = 7):
        """오래된 로컬 백업 삭제"""
        import time
        cutoff_time = time.time() - (retention_days * 86400)

        for backup_file in self.backup_dir.glob("*.sql.gz"):
            if backup_file.stat().st_mtime < cutoff_time:
                backup_file.unlink()
                print(f"🗑️ Deleted old backup: {backup_file.name}")


# 사용 예시
if __name__ == "__main__":
    config = {
        'host': 'localhost',
        'database': 'myapp',
        'user': 'backup_user',
        'password': 'secure_password'
    }

    backup = DatabaseBackup(config, s3_bucket="my-db-backups")

    # 일일 풀 백업
    backup_file = backup.create_postgresql_backup("full")

    # S3에 업로드 (오프사이트 보관)
    backup.upload_to_s3(backup_file, retention_days=30)

    # 7일 이상 된 로컬 백업 삭제
    backup.cleanup_old_backups(retention_days=7)
// 데이터베이스 백업 및 S3 업로드 - Node.js
const { spawn } = require('child_process');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const { createReadStream, createWriteStream, unlinkSync } = require('fs');
const { createGzip } = require('zlib');
const { pipeline } = require('stream/promises');
const path = require('path');

class DatabaseBackup {
    constructor(dbConfig, s3Config) {
        this.dbConfig = dbConfig;
        this.s3Client = new S3Client({ region: s3Config.region });
        this.s3Bucket = s3Config.bucket;
        this.backupDir = '/var/backups/db';
    }

    /**
     * PostgreSQL 백업 생성
     */
    async createPostgresBackup() {
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `${this.dbConfig.database}_${timestamp}.sql`;
        const backupPath = path.join(this.backupDir, filename);
        const compressedPath = `${backupPath}.gz`;

        return new Promise((resolve, reject) => {
            const env = { ...process.env, PGPASSWORD: this.dbConfig.password };

            const pgDump = spawn('pg_dump', [
                '-h', this.dbConfig.host,
                '-p', this.dbConfig.port || '5432',
                '-U', this.dbConfig.user,
                '-d', this.dbConfig.database,
                '-F', 'p',
                '--no-owner'
            ], { env });

            const writeStream = createWriteStream(backupPath);
            pgDump.stdout.pipe(writeStream);

            pgDump.stderr.on('data', (data) => {
                console.error(`pg_dump stderr: ${data}`);
            });

            pgDump.on('close', async (code) => {
                if (code !== 0) {
                    reject(new Error(`pg_dump exited with code ${code}`));
                    return;
                }

                // Gzip 압축
                await pipeline(
                    createReadStream(backupPath),
                    createGzip(),
                    createWriteStream(compressedPath)
                );

                // 원본 삭제
                unlinkSync(backupPath);

                console.log(`✅ Backup created: ${compressedPath}`);
                resolve(compressedPath);
            });
        });
    }

    /**
     * MySQL 백업 생성
     */
    async createMysqlBackup() {
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `${this.dbConfig.database}_${timestamp}.sql.gz`;
        const backupPath = path.join(this.backupDir, filename);

        return new Promise((resolve, reject) => {
            const mysqldump = spawn('mysqldump', [
                '-h', this.dbConfig.host,
                '-P', this.dbConfig.port || '3306',
                '-u', this.dbConfig.user,
                `-p${this.dbConfig.password}`,
                '--single-transaction',  // InnoDB 일관성 보장
                '--routines',            // 스토어드 프로시저 포함
                '--triggers',            // 트리거 포함
                this.dbConfig.database
            ]);

            const gzip = createGzip();
            const writeStream = createWriteStream(backupPath);

            mysqldump.stdout.pipe(gzip).pipe(writeStream);

            mysqldump.on('close', (code) => {
                if (code === 0) {
                    console.log(`✅ MySQL backup created: ${backupPath}`);
                    resolve(backupPath);
                } else {
                    reject(new Error(`mysqldump exited with code ${code}`));
                }
            });
        });
    }

    /**
     * S3에 백업 업로드
     */
    async uploadToS3(backupPath) {
        const filename = path.basename(backupPath);
        const s3Key = `backups/${filename}`;

        const command = new PutObjectCommand({
            Bucket: this.s3Bucket,
            Key: s3Key,
            Body: createReadStream(backupPath),
            ContentType: 'application/gzip',
            Tagging: 'backup-type=automated&retention=30days'
        });

        await this.s3Client.send(command);
        console.log(`✅ Uploaded to S3: s3://${this.s3Bucket}/${s3Key}`);

        return `s3://${this.s3Bucket}/${s3Key}`;
    }

    /**
     * 전체 백업 워크플로우
     */
    async runBackupWorkflow() {
        try {
            console.log('🚀 Starting backup workflow...');

            // 1. 백업 생성
            const backupPath = await this.createPostgresBackup();

            // 2. S3 업로드 (오프사이트 보관)
            const s3Uri = await this.uploadToS3(backupPath);

            // 3. 알림 전송 (Slack, Email 등)
            console.log(`✅ Backup complete: ${s3Uri}`);

            return { success: true, location: s3Uri };
        } catch (error) {
            console.error(`❌ Backup failed: ${error.message}`);
            // 실패 알림 전송
            throw error;
        }
    }
}

// 사용 예시
const backup = new DatabaseBackup(
    {
        host: 'localhost',
        database: 'myapp',
        user: 'backup_user',
        password: 'secure_password'
    },
    {
        region: 'ap-northeast-2',
        bucket: 'my-db-backups'
    }
);

backup.runBackupWorkflow();
# ============================================
# PostgreSQL 백업 명령어
# ============================================

# 1. 논리적 백업 (pg_dump)
# 단일 데이터베이스 백업
pg_dump -h localhost -U postgres -d mydb > backup.sql

# 압축하여 백업
pg_dump -h localhost -U postgres -d mydb | gzip > backup.sql.gz

# Custom 포맷 (병렬 복원 가능)
pg_dump -h localhost -U postgres -d mydb -F c -f backup.dump

# 특정 테이블만 백업
pg_dump -h localhost -U postgres -d mydb -t users -t orders > tables.sql

# 2. 전체 클러스터 백업
pg_dumpall -h localhost -U postgres > all_databases.sql

# 3. 물리적 백업 (pg_basebackup) - PITR 지원
pg_basebackup -h localhost -U replication -D /backup/base -Ft -z -P

# 4. 복원
psql -h localhost -U postgres -d mydb < backup.sql
pg_restore -h localhost -U postgres -d mydb backup.dump


# ============================================
# MySQL 백업 명령어
# ============================================

# 1. 단일 데이터베이스 백업
mysqldump -h localhost -u root -p mydb > backup.sql

# 트랜잭션 일관성 보장 (InnoDB)
mysqldump -h localhost -u root -p \
    --single-transaction \
    --routines \
    --triggers \
    mydb > backup.sql

# 압축하여 백업
mysqldump -h localhost -u root -p mydb | gzip > backup.sql.gz

# 2. 전체 백업
mysqldump -h localhost -u root -p --all-databases > all_databases.sql

# 3. 바이너리 로그 위치 포함 (PITR용)
mysqldump -h localhost -u root -p \
    --single-transaction \
    --master-data=2 \
    mydb > backup_with_position.sql

# 4. 복원
mysql -h localhost -u root -p mydb < backup.sql
gunzip < backup.sql.gz | mysql -h localhost -u root -p mydb


# ============================================
# 자동화 스크립트 (cron)
# ============================================

# /etc/cron.d/db-backup
# 매일 새벽 2시 풀 백업
0 2 * * * postgres /opt/scripts/daily_backup.sh

# daily_backup.sh 예시
#!/bin/bash
DATE=$(date +%Y%m%d)
BACKUP_DIR="/var/backups/postgresql"
S3_BUCKET="my-db-backups"

# 백업 생성
pg_dump -h localhost -U backup_user -d production \
    -F c -f "$BACKUP_DIR/production_$DATE.dump"

# S3 업로드
aws s3 cp "$BACKUP_DIR/production_$DATE.dump" \
    "s3://$S3_BUCKET/daily/production_$DATE.dump"

# 7일 이상 된 로컬 백업 삭제
find $BACKUP_DIR -name "*.dump" -mtime +7 -delete

echo "Backup completed: production_$DATE.dump"

🗣️ Say It Like This in Practice

💬 In a Disaster Recovery Planning Meeting
"We have applied the 3-2-1 backup rule. We keep 7 days of full backups locally, 30 days on S3, and 1 year on Glacier. RTO is 2 hours and RPO is 1 hour, and we support PITR through WAL archiving."
💬 When Deciding on a Backup Strategy
"Since the data exceeds 100GB, daily full backups are inefficient. Let's go with a combination of a weekly full backup and daily incremental backups. We'll take physical backups with pg_basebackup and enable point-in-time recovery through WAL archiving."
💬 In a Post-Incident Review
"We had backups, but we were caught off guard because we had not tested restoration. From now on, we will verify the actual restoration procedure through quarterly DR drills, and measure the restoration time to confirm whether we meet the RTO."

⚠️ Cautions & Best Practices

❌
Only backing up and skipping restore tests

If the backup file is corrupted or there is a problem with the restoration procedure, recovery will be impossible during an actual outage. Perform restore tests regularly.

❌
Keeping backups only on the same server

If the server fails or the disk is damaged, the backups are lost along with it. Be sure to keep copies offsite (S3, a different region).

❌
Service locks during backup

Using MyISAM tables or incorrect options causes table locks. Use InnoDB with the --single-transaction option for non-disruptive backups.

✅
Backup Best Practices

Follow the 3-2-1 rule, encrypt backups (AES-256), automate restore tests, set up backup monitoring and alerts, and determine the backup frequency based on RPO/RTO.

🔗 Related Terms

📚 Learn More