Created
July 9, 2015 21:42
-
-
Save nazar-pc/8569925a95b21edc57de to your computer and use it in GitHub Desktop.
Docker containers backup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've saved this file as
/etc/cron.daily/backup-docker-daily
to have daily backups.