Skip to content

Instantly share code, notes, and snippets.

@nazar-pc
Created July 9, 2015 21:42
Show Gist options
  • Save nazar-pc/8569925a95b21edc57de to your computer and use it in GitHub Desktop.
Save nazar-pc/8569925a95b21edc57de to your computer and use it in GitHub Desktop.
Docker containers backup
#!/usr/bin/php
<?php
$local_backup_dir = '/backup-local';
$target_backup_dir = '/backup';
$backup_prefix = '';
$backup_suffix = '-'.date('l');
/**
* We'll make backups to local directory first and then move to target
*/
chdir($local_backup_dir);
/**
* Remove old files if any
*/
exec('rm *');
/**
* Get list of all containers, including stopped
*/
exec('docker ps -a', $docker_containers);
/**
* Remove first line of the output
*/
array_shift($docker_containers);
foreach ($docker_containers as $container) {
$container = explode(' ', $container);
$container = array_pop($container);
/**
* Do not backup containers created by docker-compose, as they are stateless
*/
if (preg_match('/.+_.+_[0-9]+$/', $container)) {
continue;
}
/**
* Get more details about container
*/
unset($details);
exec("docker inspect $container", $details);
$details = json_decode(implode('', $details), true)[0];
$backup_file_name = $backup_prefix.$container.$backup_suffix;
/**
* If this is nazarpc/webserver:data container - we need to backup data only using special container, otherwise use normal container export
*/
if ($details['Config']['Image'] === 'nazarpc/webserver:data') {
exec("docker run --rm --volumes-from $container -v /$local_backup_dir:/backup --env BACKUP_FILENAME=$backup_file_name nazarpc/webserver:backup");
} else {
exec("docker export $container > $backup_file_name.tar");
}
}
/**
* Compress backups to decrease size
*/
exec("bzip2 -f *.tar");
/**
* Move to target
*/
exec("mv -f *.tar.bz2 /$target_backup_dir");
@nazar-pc
Copy link
Author

nazar-pc commented Jul 9, 2015

I've saved this file as /etc/cron.daily/backup-docker-daily to have daily backups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment