Skip to content

Instantly share code, notes, and snippets.

@qxo
Last active August 29, 2015 14:05
Show Gist options
  • Save qxo/35b5fc84a3a200ed3707 to your computer and use it in GitHub Desktop.
Save qxo/35b5fc84a3a200ed3707 to your computer and use it in GitHub Desktop.
merge old image dir to new base image
#!/bin/bash
# a script for merge one image dir to another
if [ -z "$1" -o -z "$2" -o -z "$3" ] ; then
echo 'usage:'
echo ' docker-merge-image-dir merge-into-image-tag old-image-tag old-image-dir [in-container-cmd,out-container-cmd]'
echo ' after merge old-image-tag = merge-into-image-tag + old-image-dir '
exit
fi
tmpImg="tmp-img-$RANDOM"
targetImgTag="$2"
latestImgTag="$1"
mergedImagDir="$3"
echo "temp image name:$tmpImg"
echo "old-image-tag:$targetImgTag"
echo "old-image-dir(need to be merged):$mergedImagDir"
echo "merge-into-image-tag:$latestImgTag"
echo "in-container-cmd(run after merged success in container):$4"
echo "out-container-cmd(run after $mergedImagDir copy to temp dir in host):$5"
echo "Are you sure?[Y=yes]"
read ok
if [ "$ok" = "Y" ] ; then
if [ -n "$4" ] ; then
optExpr="$4"
else
optExpr="echo 'no expr'"
fi
echo "pull image first ? input N to cancel "
read ok
if [ ! "$ok" = "N" ] ; then
docker pull $targetImgTag
docker pull $latestImgTag
fi
tmpDir=$(mktemp -d -t tmp-imageXXX)
echo "temp dir:$tmpDir"
echo "create old image container for copy"
#CID=$(docker run -d -i -t $targetImgTag echo)
CID="ocid-$RANDOM"
echo "old image container:$CID"
echo "merge old image to new image container"
docker run -i --name $CID -v $tmpDir:/x -t $targetImgTag bash -c " rsync -vrtopg -l --progress -W -B 2048 $mergedImagDir/* /x/ "
echo $tmpDir
echo "data size:$(du -sm $tmpDir)"
ls -l "$tmpDir/"
docker rm -f $CID
if [ -n "$5" ] ; then
echo "$5"
eval $5
fi
newCID="c-$RANDOM"
echo "new image container:$newCID"
docker run -i -t --name $newCID -v $tmpDir:/x $latestImgTag \
sh -c " ( !(test -d $mergedImagDir) && mkdir -p $mergedImagDir || true ) && \
rsync -vrtopg -l --progress -B 2048 /x/* $mergedImagDir/ "
r=$?
echo "cmd result:$r"
if [ $r -eq 0 ] ; then
echo "commit merged to image:$targetImgTag"
docker commit $newCID $tmpImg && \
docker rm -f $newCID && \
docker run -i -t --name $newCID $tmpImg bash -c " $optExpr && rm -rf /x /tmp/* /var/tmp/* " && \
docker commit $newCID $tmpImg && \
docker rm -f $newCID && \
docker tag $tmpImg $targetImgTag && \
docker rmi $tmpImg && \
docker run -i -t --rm $targetImgTag du -sm $mergedImagDir
test $? -eq 0 && rm -rf $tmpDir
else
echo "something wrong,checking it !"
fi
else
echo "do nothing"
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment