Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Save and load docker images in batch
#!/bin/bash
readonly DB_FILE="$(pwd)/images.db"
readonly IMG_DIR="$(pwd)/images"
save-images() {
echo "Create ${DB_FILE}"
echo "$(docker images|grep -v 'IMAGE ID'|awk '{printf("%s %s %s\n", $1, $2, $3)}'|column -t)" > "${DB_FILE}"
echo "Read ${DB_FILE}"
local images
while read -r image; do
images+=("$image");
done <<< "$(cat ${DB_FILE})"
echo "Create ${IMG_DIR}"
if [[ ! -d "${IMG_DIR}" ]]; then
mkdir "${IMG_DIR}"
fi
local name tag id
for image in "${images[@]}"; do
name=$(echo $image|awk '{print $1}')
tag=$(echo $image|awk '{print $2}')
id=$(echo $image|awk '{print $3}')
if [[ "${id}" != "" ]]; then
local imgPath="${IMG_DIR}/${id}.dim"
if [[ ! -f "${imgPath}" ]] ; then
echo "[DEBUG] save ${id} ${name}:${tag} to ${imgPath}"
(time docker save -o "${imgPath}" ${name}:${tag}) 2>&1 | grep real
else
echo "[DEBUG] ${id} ${name}:${tag} already saved"
fi
fi
done
}
load-images() {
if [[ ! -f "${DB_FILE}" ]]; then
echo "No ${DB_FILE} to read"
exit 0
fi
if [[ ! -d "${IMG_DIR}" ]]; then
echo "No ${IMG_DIR} to load images"
exit 0
fi
echo "Read ${DB_FILE}"
local images
while read -r image; do
images+=("$image");
done <<< "$(cat ${DB_FILE})"
local name tag id
for image in "${images[@]}"; do
name=$(echo $image|awk '{print $1}')
tag=$(echo $image|awk '{print $2}')
id=$(echo $image|awk '{print $3}')
if [[ "${id}" != "" ]]; then
local imgPath="${IMG_DIR}/${id}.dim"
if [[ "$(docker images|grep ${id} | grep ${name} | grep ${tag})" == "" ]]; then
if [[ "$(docker images|grep ${id})" == "" ]]; then
echo "[DEBUG] load ${id} ${name}:${tag} from ${imgPath}"
docker load -i "${imgPath}"
else
echo "[DEBUG] tag ${id} as ${name}:${tag}"
docker tag ${id} ${name}:${tag}
fi
else
echo "[DEBUG] ${id} ${name}:${tag} already loaded"
fi
fi
done
}
$@
@ellerbrock

This comment has been minimized.

Copy link

ellerbrock commented Apr 12, 2017

very cool! thanks a lot!
also nice to see someone knows how to write nice clean bash code.

@bigwhite

This comment has been minimized.

Copy link

bigwhite commented Nov 8, 2017

Good tool!It is just what I am looking for. Thanks! And it would be better to first remove all the "dangling images" in save function.

@bsienn

This comment has been minimized.

Copy link

bsienn commented Jan 1, 2018

I get this error on windows 10:

image

@cjreysayago

This comment has been minimized.

Copy link

cjreysayago commented Jan 22, 2018

Thanks! Nice Job

@hm-dusk

This comment has been minimized.

Copy link

hm-dusk commented Nov 6, 2018

Thanks!

@enoch85

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.