Last active
May 5, 2024 16:42
-
-
Save mvasin/06200f033fdfbee2cb558a6bbe130709 to your computer and use it in GitHub Desktop.
Export a Docker volume to a .tar / Import into Docker volume from a .tar / Duplicate volumes (via tar)
This file contains hidden or 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
# Usage: export_volume volume_name | |
# export_volume volume_name > file.tar | |
# | |
# prints to STDOUT a volume in .tar format | |
export_volume() { | |
# Quit if volume name is not specified | |
vol=${1:?} | |
# If there is no such container, a new container will be created, we don't need that | |
docker volume inspect $vol > /dev/null || (echo "Container specified for export doesn't exist" && return 1) | |
# Export container contents to STDOUT in an uncompressed tar format | |
docker run --rm -i -v $vol:/vol alpine tar -C /vol -c . | |
} | |
# Usage: import_volume volume_name | |
# cat file.tar | import_volume volume_name | |
# | |
# Unpacks a tar archive passed in to STDIN to volume_name volume. | |
# The volume may not exist in advance, otherwise must be empty. | |
import_volume() { | |
# Quit if volume name is not specified | |
vol=${1:?} | |
# If the container does not exist, create it | |
docker volume inspect $vol > /dev/null 2>&1 || docker volume create $vol > /dev/null | |
# If the container is not empty, quit (don't mess it up) | |
docker run --rm -v $vol:/vol alpine sh -c "test \"\`ls -A /vol\`\"" && return 1 | |
# Finally, untar into a volume | |
docker run --rm -i -v $vol:/vol alpine tar -C /vol -xf - | |
} | |
# Usage: duplicate_volume from_volume_name to_volume_name | |
duplicate_volume() { | |
source_volume=${1:?} | |
destination_volume=${2:?} | |
export_volume $source_volume | import_volume $destination_volume | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment