Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Last active May 19, 2023 16:31
Show Gist options
  • Save erikvullings/2d22d5ab6bf0538374404110ff69c61b to your computer and use it in GitHub Desktop.
Save erikvullings/2d22d5ab6bf0538374404110ff69c61b to your computer and use it in GitHub Desktop.
Create a new Docker volume and fill it with local data

Create Docker volume

When moving from a local development environment to the cloud, e.g. Docker swarm or Kubernetes, you often need a way to access local files. However, in the cloud your local file system cannot be accessed anymore, so you need a way to copy your local files to a volume and mount that instead. This is the purpose of the script. You supply it with the volume name (e.g. schemas) and the local folder containing the schemas, e.g. ../../schemas, and a schemas volume is created, containing all data that is copied into the container.

./create_volume.sh schemas ../../schemas
#!/bin/bash
# Help function
display_help() {
echo "Usage: ./create_volume.sh <volume_name> <source_directory>"
echo ""
echo "Arguments:"
echo " <volume_name> Name for the Docker volume"
echo " <source_directory> Path to the source directory on the host machine (relative or absolute)"
}
# Check if help option is passed
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
display_help
exit 0
fi
# Check if at least two arguments are provided
if [ $# -lt 2 ]; then
echo "Error: Invalid number of arguments"
display_help
exit 1
fi
# Arguments
volume_name=$1
source_directory=$2
# Create the volume (skipped if the volume already exists)
docker volume create "$volume_name" >/dev/null
# Create a temporary container to perform the copy
container_id=$(docker create -v "$volume_name:/target" alpine)
# Copy the data from the source directory to the volume using the container
docker cp "$source_directory/." "$container_id:/target"
# Remove the temporary container
docker rm "$container_id" >/dev/null
echo "Data copied successfully to the Docker volume."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment