# VPS Snapshots

Complete guide to creating, managing, and restoring VPS snapshots for backup and cloning purposes.

## What are Snapshots?

Snapshots are point-in-time copies of your VPS instance, including:

- **Operating system** and all files
- **Applications** and configurations
- **Data** stored on the instance
- **Complete system state** at capture time

### Snapshots vs Backups

| Feature | Snapshots | Traditional Backups |
|---------|-----------|-------------------|
| **Speed** | Very fast (minutes) | Slower (hours) |
| **Downtime** | None required | May require downtime |
| **Restore** | Complete system restore | File-level restore |
| **Use Case** | System cloning, migrations | Data recovery |
| **Storage** | Block-level | File-level |

## Why Use Snapshots?

### Backup Before Changes
Take a snapshot before:
- System updates
- Application upgrades
- Configuration changes
- Installing new software
- Database migrations

### Disaster Recovery
- Quick recovery from failures
- Protection against mistakes
- Rollback bad deployments
- Restore corrupted systems

### Cloning & Scaling
- Create identical instances
- Scale horizontally
- Test environments
- Development copies

### Migration
- Move to a different host
- Upgrade instance size
- Change configurations
- Platform migration

## Automated Snapshots

Every running VPS is snapshotted **automatically on a daily schedule** — no setup required. Automated snapshots:

- Run only while the instance is **running**, so you're never charged for wasted backups of stopped instances
- Are kept for a rolling **retention window** and cleaned up automatically once they age out
- Appear alongside your manual snapshots (tagged **automated**) and can be restored or cloned the same way
- Are additionally copied **offsite** for 3-2-1-compliant backups (see below)

You can still take **manual** snapshots anytime before risky changes — those are kept until you delete them.

### Offsite Backups (3-2-1)

Beyond the primary snapshot stored with your instance, snapshots are exported to **offsite storage**, giving you a 3-2-1-compliant backup — multiple copies, on separate storage, one off-site. That offsite export is also what makes **cloning a snapshot into a brand-new instance** possible. If an export fails, you can retry it from the Snapshots page.

## Creating Snapshots

### Via Dashboard

1. **Navigate** to **Pods** (VPS)
2. **Click** on your instance name
3. **Go to** **Snapshots** tab
4. **Click** **Create Snapshot**
5. **Enter** snapshot details:
   - **Name**: Descriptive name
   - **Description**: Purpose and context
6. **Click** **Create**

**Creation Time**: 2-5 minutes depending on disk size

### Snapshot Naming Best Practices

**Good Names**:
```
pre-update-2024-10-11
before-nginx-upgrade
production-backup-daily
staging-clone-v2
migration-source
```

**Poor Names**:
```
snapshot1
backup
test
my-snapshot
```

### Naming Convention

```
[environment]-[purpose]-[date]
prod-pre-deploy-2024-10-11
staging-backup-2024-10-11
dev-clone-2024-10-11
```

## Snapshot Details

### What's Included

✅ **Operating System**: All OS files  
✅ **Applications**: Installed software  
✅ **Configurations**: All config files  
✅ **Data**: Application data, databases  
✅ **Users**: User accounts and permissions  
✅ **Logs**: System and application logs  

### What's NOT Included

❌ **RAM Contents**: Active memory state  
❌ **Network Connections**: Active connections  
❌ **Temporary Files**: /tmp contents may vary  
❌ **Process State**: Running processes  

### Best Practices Before Snapshot

1. **Stop Services** (optional but recommended):
   ```bash
   # Stop database
   sudo systemctl stop mysql
   
   # Stop application
   sudo systemctl stop nginx
   ```

2. **Flush Caches**:
   ```bash
   # Sync filesystem
   sync
   
   # Drop caches
   sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
   ```

3. **Database Backup**:
   ```bash
   # MySQL
   mysqldump -u root -p --all-databases > backup.sql
   
   # PostgreSQL
   pg_dumpall > backup.sql
   ```

4. **Document State**:
   - Running services
   - Important processes
   - Configuration details

## Managing Snapshots

### View Snapshots

1. Go to VPS instance page
2. Click **Snapshots** tab
3. See all snapshots:
   - Name and description
   - Creation date
   - Size
   - Status

### Snapshot Statuses

- **Creating**: Snapshot in progress
- **Available**: Ready to use
- **Restoring**: Being restored
- **Deleting**: Being removed
- **Error**: Failed creation/restore

Snapshot status and progress update **live** on the page — no refresh needed — including offsite export progress.

### Delete Snapshot

**Warning**: Deletion is permanent!

1. Go to **Snapshots** tab
2. Click **Delete** next to snapshot
3. Confirm deletion
4. Snapshot removed immediately

**Note**: You're charged for snapshot storage until deleted.

## Restoring from Snapshots

### Restore to Existing Instance

**Warning**: This will overwrite your current instance!

You can restore from either the per-instance **Snapshots** tab or the centralized **Snapshots** page at `/snapshots`.

1. **Backup current data** if needed
2. Go to **Snapshots** tab on the instance page, or navigate to **Snapshots** in the sidebar
3. Click the **Restore** button (rotate icon) next to the snapshot
4. Confirm the action in the warning dialog
5. Wait 5-10 minutes

**What Happens**:
- The VM is stopped if running
- Disk data is replaced with the snapshot contents
- The VM is restarted automatically
- Any data created after the snapshot will be lost

### Create New Instance from Snapshot (Clone)

**Safer option** - doesn't affect the existing instance.

Cloning a VPS from a snapshot uses the **export-based clone** workflow, which requires an offsite backup to be completed first (3-2-1 compliant).

**Prerequisites**:
- Snapshot status must be **Ready**
- Export (offsite backup) must be **Completed**
- No other clone operation in progress for this snapshot

**Steps**:
1. Go to the **Snapshots** tab on the instance page, or navigate to **Snapshots** in the sidebar
2. Click the **Clone** button (copy icon) next to an eligible snapshot
3. Enter a **name** for the new VPS instance (lowercase letters, numbers, and hyphens; 3-32 characters)
4. Click **Clone Instance**

**Clone Process**:
The clone operation downloads the snapshot data from offsite storage, decompresses it, and deploys a new VPS. You can track progress through these stages:
- **Preparing** - Setting up the clone operation
- **Downloading** - Retrieving snapshot data from S3 storage
- **Decompressing** - Extracting the disk image
- **Importing** - Creating the new disk volume
- **Deploying** - Launching the new VPS instance

**What the New VPS Inherits**:
- Operating system and all files from the snapshot
- Disk size and resource profile from the original instance

**What's New**:
- New IPv4 (and optionally IPv6) address
- New MAC address
- New instance name

**Duration**: 10-30 minutes depending on disk size.

## Centralized Snapshots Page

Navigate to **Snapshots** in the sidebar to access the centralized snapshots page at `/snapshots`. This page shows all snapshot types (VPS, Cache, Database) in a single view.

**Features**:
- **Filter** by instance type (VPS, Cache, Database), status, and automated/manual
- **Search** by instance name
- **Restore** any snapshot to its parent instance
- **Clone** to create a new instance from a snapshot
- **Delete** snapshots that are no longer needed
- **Retry** failed offsite backups

### After Restore

1. **Verify System**:
   ```bash
   # Check system status
   uptime
   df -h
   free -h
   
   # Verify services
   sudo systemctl status nginx
   sudo systemctl status mysql
   ```

2. **Update Configurations**:
   - Update IP addresses
   - Update DNS records
   - Update environment variables
   - Update API endpoints

3. **Start Services**:
   ```bash
   sudo systemctl start nginx
   sudo systemctl start mysql
   sudo systemctl start your-app
   ```

## Snapshot Use Cases

### Use Case 1: Safe System Updates

**Scenario**: Ubuntu system update

```bash
# 1. Create snapshot via dashboard
# Name: "pre-update-2024-10-11"

# 2. Perform update
sudo apt update
sudo apt upgrade -y
sudo apt dist-upgrade -y

# 3. Test system
# If problems occur, restore from snapshot
# If all good, keep running

# 4. Delete old snapshot after confirmed working
```

### Use Case 2: Application Deployment

**Scenario**: Deploy new application version

```bash
# 1. Create snapshot
# Name: "pre-deploy-v2.0"

# 2. Deploy new version
git pull origin main
npm install
npm run build
sudo systemctl restart app

# 3. Test thoroughly
# If issues, restore snapshot
# If successful, keep and delete old snapshot
```

### Use Case 3: Development Environment

**Scenario**: Create dev copy of production

1. **Create snapshot** of production instance
2. **Restore** to new instance
3. **Rename** new instance to "dev-environment"
4. **Update configurations**:
   - Change database credentials
   - Update API keys (use test keys)
   - Disable production integrations
   - Update application URLs

### Use Case 4: Horizontal Scaling

**Scenario**: Add more web servers

1. **Prepare** one server perfectly:
   - Install all software
   - Configure everything
   - Test thoroughly

2. **Create snapshot** "web-server-template"

3. **Create multiple instances** from snapshot:
   - web-server-01
   - web-server-02
   - web-server-03

4. **Configure load balancer** to distribute traffic

### Use Case 5: Migration

**Scenario**: Move to larger instance

1. **Create snapshot** of current instance
2. **Create new instance** from snapshot
   - Choose a larger profile
3. **Test** new instance
4. **Update DNS** to point to new instance
5. **Delete** old instance
6. **Delete** old snapshot

## Automation with API

### Create Snapshot

```python
import requests

headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Content-Type": "application/json"
}

data = {
    "name": f"auto-backup-{datetime.now().strftime('%Y-%m-%d')}",
    "description": "Automated daily backup"
}

response = requests.post(
    "https://api.danubedata.ro/v1/vps/vps-abc123/snapshots",
    headers=headers,
    json=data
)

snapshot = response.json()
print(f"Snapshot created: {snapshot['data']['id']}")
```

### List Snapshots

```python
response = requests.get(
    "https://api.danubedata.ro/v1/vps/vps-abc123/snapshots",
    headers=headers
)

snapshots = response.json()["data"]
for snap in snapshots:
    print(f"{snap['name']}: {snap['created_at']}")
```

### Automated Daily Backup Script

```python
#!/usr/bin/env python3
import requests
import os
from datetime import datetime, timedelta

API_TOKEN = os.environ['DANUBEDATA_API_TOKEN']
VPS_ID = "vps-abc123"
RETENTION_DAYS = 7

headers = {
    "Authorization": f"Bearer {API_TOKEN}",
    "Content-Type": "application/json"
}

# Create new snapshot
data = {
    "name": f"daily-backup-{datetime.now().strftime('%Y-%m-%d')}",
    "description": f"Automated backup - {datetime.now()}"
}

response = requests.post(
    f"https://api.danubedata.ro/v1/vps/{VPS_ID}/snapshots",
    headers=headers,
    json=data
)

if response.status_code == 201:
    print(f"Snapshot created successfully")
else:
    print(f"Error: {response.json()}")
    exit(1)

# Delete old snapshots
response = requests.get(
    f"https://api.danubedata.ro/v1/vps/{VPS_ID}/snapshots",
    headers=headers
)

snapshots = response.json()["data"]
cutoff_date = datetime.now() - timedelta(days=RETENTION_DAYS)

for snap in snapshots:
    snap_date = datetime.fromisoformat(snap['created_at'].replace('Z', '+00:00'))
    if snap_date < cutoff_date and snap['name'].startswith('daily-backup'):
        print(f"Deleting old snapshot: {snap['name']}")
        requests.delete(
            f"https://api.danubedata.ro/v1/vps/{VPS_ID}/snapshots/{snap['id']}",
            headers=headers
        )
```

**Schedule with Cron**:
```bash
# Add to crontab
0 2 * * * /usr/local/bin/backup-vps.py
```

## Snapshot Pricing

### Storage Costs

- **Price**: €0.073 per GB per month
- **Billed**: Hourly (prorated)
- **Size**: Based on used disk space

### Cost Examples

| Instance Size | Used Space | Monthly Cost |
|---------------|------------|--------------|
| 20 GB disk | 10 GB used | €0.73 |
| 40 GB disk | 25 GB used | €1.83 |
| 80 GB disk | 40 GB used | €2.92 |
| 160 GB disk | 80 GB used | €5.84 |

### Cost Optimization

1. **Delete old snapshots** regularly
2. **Clean disk** before snapshot:
   ```bash
   sudo apt clean
   sudo journalctl --vacuum-time=7d
   docker system prune -a
   ```
3. **Keep only necessary snapshots**
4. **Use compression** before snapshot
5. **Remove unused files**

## Best Practices

### Regular Snapshots

**Daily Production**:
- Before any changes
- Automated nightly backups
- Keep 7 days

**Weekly Development**:
- End of sprint
- Before major updates
- Keep 4 weeks

**Pre-Change Always**:
- Before system updates
- Before deployments
- Before configuration changes

### Naming Strategy

```
[frequency]-[environment]-[date]
daily-prod-2024-10-11
weekly-staging-2024-10-11
pre-deploy-prod-2024-10-11
```

### Testing Restores

**Monthly**: Test restore process
1. Create test instance from snapshot
2. Verify all services work
3. Confirm data integrity
4. Document restore time
5. Delete test instance

### Documentation

Keep a snapshot log:
```
Date       | Name              | Purpose           | Retention
-----------|-------------------|-------------------|----------
2024-10-11 | pre-update-v2     | Before Ubuntu 24  | 30 days
2024-10-11 | daily-prod        | Daily backup      | 7 days
2024-10-10 | pre-deploy-api    | Before API v3     | 14 days
```

## Troubleshooting

### Snapshot Creation Fails

**Check**:
1. Disk space available
2. Instance is running
3. No other operations in progress
4. Account limits not exceeded

**Solution**:
```bash
# Free up space
sudo apt clean
sudo journalctl --vacuum-time=7d
rm -rf /tmp/*

# Check disk
df -h
```

### Restore Fails

**Possible Causes**:
- Insufficient resources
- Snapshot corrupted
- Network issues

**Solution**:
1. Try again
2. Contact support
3. Use different snapshot
4. Check system logs

### Slow Snapshot Creation

**Factors**:
- Disk size
- Data amount
- Disk activity
- Network speed

**Optimization**:
- Stop services temporarily
- Reduce disk I/O
- Schedule during low-traffic
- Clean disk before snapshot

## Limitations

### Size Limits
- Maximum snapshot size: Based on disk size
- Storage per account: Check account limits

### Quantity Limits
- Snapshots per instance: 50 (default)
- Request increase if needed

### Region
- Snapshots are stored redundantly in the same region (Falkenstein, Germany)
- For offsite copies, download or export the snapshot

### Time Limits
- Creation time: 2-10 minutes
- Restore time: 5-15 minutes
- Depends on size

## Security Considerations

### Data Protection

✅ **Encrypted at Rest**: All snapshots encrypted  
✅ **Access Control**: Only account members can access  
✅ **Isolated Storage**: Separate from instance storage  
✅ **Backup Redundancy**: Multiple copies maintained  

### Sensitive Data

**Before Snapshot**:
1. Review for sensitive data
2. Remove temporary secrets
3. Clear logs with sensitive info
4. Document included credentials

**After Restore**:
1. Rotate credentials
2. Update API keys
3. Change passwords
4. Verify access controls

## Next Steps

- [VPS Management](https://docs.danubedata.ro/vps-managing)
- [VPS SSH Access](https://docs.danubedata.ro/vps-ssh)
- [Backup Strategies](https://docs.danubedata.ro/databases-backups)
- [Disaster Recovery](https://docs.danubedata.ro/vps-managing)

Need help with snapshots? Contact support through the dashboard.

