Skip to content

Instantly share code, notes, and snippets.

@arruw
Last active February 10, 2019 20:05
Show Gist options
  • Save arruw/a788bafeacf19b747273054ed83384c1 to your computer and use it in GitHub Desktop.
Save arruw/a788bafeacf19b747273054ed83384c1 to your computer and use it in GitHub Desktop.
Backup Docker named volumes (Docker for Windows)
param (
[Parameter(Mandatory = $true, HelpMessage = "List all named volumes you want to backup. <volume1,volume2,volume3>")]
[string[]] $Volumes,
[Parameter(Mandatory = $true, HelpMessage = "Backup path")]
[string] $Path
)
$ErrorActionPreference = "Stop"
"Checking volumes..."
foreach ($volume in $Volumes) {
$out = ""
Invoke-Expression "docker ps -q -f 'volume=${volume}'" | Tee-Object -Variable out > $null
$lines = $out | Measure-Object -Line
$count = $lines.Count
if (($count -gt 0) -and ($lines[0].Lines -gt 0)) {
"Volume ${volume} is currenty in use by ${count} container(s) (${out}). First stop this container and then try again."
"Exiting..."
exit 1
}
}
"Preparing..."
$dockerRun = "docker run --rm -it -d "
foreach ($volume in $Volumes) {
$dockerRun += "-v ${volume}:/backup/${volume}:ro "
}
$dockerRun += "--name backup alpine"
Invoke-Expression $dockerRun > $null
Invoke-Expression "docker exec backup apk add zip" > $null
foreach ($volume in $Volumes) {
"Copying ${volume}..."
Invoke-Expression "docker exec -w /backup/${volume} backup zip -r /tmp/${volume}.zip ." > $null
# TODO add hash value to archive name
# Invoke-Expression "docker exec backup mv /tmp/${volume}.zip ""/tmp/${volume}-`sha1sum /tmp/tk-utrip-wp.zip | awk '{print `$1;}'`.zip"""
Invoke-Expression "docker cp backup:/tmp/${volume}.zip $(Join-Path -Path $Path -ChildPath $volume).zip" > $null
}
"Cleaning up..."
Invoke-Expression "docker kill backup" > $null
# Backup Docker named volumes (Docker for Windows)
Backup named volumes (hosted inside MobyLinuxVM) to host machine.
### Find volumn names
```
docker volume ls
```
### Usage example
```
mkdir .\backup\20190210
.\backup.ps1 -Volumes volum-name-1,volume-name-2 -Path .\backup\20190210
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment