Use DBDock in your Node.js application to create backups programmatically. You don’t need to understand NestJS internals - DBDock provides a simple API that works with any Node.js backend.
Basic Setup
First, install DBDock:
Make sure you have dbdock.config.json configured (run npx dbdock init first). DBDock reads all configuration from this file automatically.
How It Works
DBDock uses a simple initialization pattern:
- Call
createDBDock() to initialize DBDock (reads from dbdock.config.json)
- Get the
BackupService from the returned context using .get(BackupService)
- Use the service methods to create backups, list backups, etc.
Think of createDBDock() as a factory function that sets up everything for you based on your config file.
Creating Backups
const { createDBDock, BackupService } = require('dbdock');
async function createBackup() {
const dbdock = await createDBDock();
const backupService = dbdock.get(BackupService);
const result = await backupService.createBackup({
format: 'plain', // 'custom' (binary), 'plain' (sql), 'directory', 'tar'
compress: true,
encrypt: true,
});
console.log(`Backup created: ${result.metadata.id}`);
console.log(`Size: ${result.metadata.formattedSize}`); // e.g. "108.3 KB"
console.log(`Path: ${result.storageKey}`);
return result;
}
createBackup().catch(console.error);
Backup Options:
compress - Enable/disable compression (default: from config)
encrypt - Enable/disable encryption (default: from config)
format - Backup format: 'custom' (default), 'plain', 'directory', 'tar'
type - Backup type: 'full' (default), 'schema', 'data'
Listing Backups
const { createDBDock, BackupService } = require('dbdock');
async function listBackups() {
const dbdock = await createDBDock();
const backupService = dbdock.get(BackupService);
const backups = await backupService.listBackups();
console.log(`Found ${backups.length} backups:`);
backups.forEach(
(backup: {
id: string;
formattedSize: string;
startTime: string | Date;
}) => {
console.log(
`- ${backup.id} (${backup.formattedSize}, created: ${backup.startTime})`
);
}
);
return backups;
}
listBackups().catch(console.error);
const { createDBDock, BackupService } = require('dbdock');
async function getBackupInfo(backupId) {
const dbdock = await createDBDock();
const backupService = dbdock.get(BackupService);
const metadata = await backupService.getBackupMetadata(backupId);
if (!metadata) {
console.log('Backup not found');
return null;
}
console.log('Backup details:', {
id: metadata.id,
size: metadata.size,
created: metadata.startTime,
encrypted: !!metadata.encryption,
compressed: metadata.compression.enabled,
});
return metadata;
}
getBackupInfo('your-backup-id').catch(console.error);
Restore functionality is currently only available via CLI (npx dbdock restore). Programmatic restore will be available in a future release.
Scheduling Backups
DBDock doesn’t include a built-in scheduler (to keep the package lightweight), but it’s easy to schedule backups using node-cron.
First, install node-cron:
npm install node-cron
npm install --save-dev @types/node-cron
Then create a scheduler script (e.g., scheduler.ts):
import { createDBDock, BackupService } from 'dbdock';
import * as cron from 'node-cron';
async function startScheduler() {
// Initialize DBDock
const dbdock = await createDBDock();
const backupService = dbdock.get(BackupService);
console.log('🚀 Backup scheduler started. Running every minute...');
// Schedule task to run every minute ('* * * * *')
// For every 5 minutes use: '*/5 * * * *'
// For every hour use: '0 * * * *'
cron.schedule('* * * * *', async () => {
try {
console.log('\n⏳ Starting scheduled backup...');
const result = await backupService.createBackup({
format: 'plain', // Use 'plain' for SQL text, 'custom' for binary
compress: true,
encrypt: true,
});
console.log(`✅ Backup successful: ${result.metadata.id}`);
console.log(`📦 Size: ${result.metadata.formattedSize}`);
console.log(`📂 Path: ${result.storageKey}`);
} catch (error) {
console.error('❌ Backup failed:', error);
}
});
}
startScheduler().catch(console.error);
The CLI dbdock schedule command manages configuration for external schedulers but does not run a daemon itself. Using node-cron as shown above is the recommended way to run scheduled backups programmatically.
Alerts
DBDock can send notifications when backups complete (success or failure) via Email and Slack. Alerts work with both programmatic usage and CLI commands.
Configuration
Configure alerts in dbdock.config.json:
{
"database": { ... },
"storage": { ... },
"backup": { ... },
"alerts": {
"email": {
"enabled": true,
"smtp": {
"host": "smtp.gmail.com",
"port": 587,
"secure": false,
"auth": {
"user": "your-email@gmail.com",
"pass": "your-app-password"
}
},
"from": "backups@yourapp.com",
"to": ["admin@yourapp.com", "devops@yourapp.com"]
},
"slack": {
"enabled": true,
"webhookUrl": "https://hooks.slack.com/services/..."
}
}
}
Using Alerts Programmatically
Once configured in dbdock.config.json, alerts are sent automatically when you create backups programmatically:
const { createDBDock, BackupService } = require('dbdock');
async function createBackupWithAlerts() {
const dbdock = await createDBDock();
const backupService = dbdock.get(BackupService);
// Alerts will be sent automatically after backup completes
const result = await backupService.createBackup({
compress: true,
encrypt: true,
});
console.log(`Backup created: ${result.metadata.id}`);
// Alerts sent to configured channels
}
createBackupWithAlerts().catch(console.error);
Alert Content
Success alerts include:
- Backup ID
- Database name
- Size (original and compressed)
- Duration
- Storage location
- Encryption status
Failure alerts include:
- Error message
- Database details
- Timestamp
- Helpful troubleshooting tips
Testing Alert Configuration
Run npx dbdock test to validate your configuration without creating a backup.
Important Notes:
- ✅ Alerts work with programmatic usage (
createBackup())
- ✅ Alerts work with scheduled backups (cron jobs in your app)
- ✅ Alerts work with CLI commands (
npx dbdock backup)
- Configuration is read from
dbdock.config.json automatically
- Multiple recipients supported in the
to array for email
- Alerts are sent asynchronously (won’t block backup completion)