ag1agw
Last Updated: September 23, 2016
·
7.997K
· frank-dspeed
Snapshot 20140412 3  2

Automated Update a Running Docker Container and CleanUP old Version of it!

The ISSU?

We have a docker container running with our application and have a new version ready that we wanna deploy and after that we wanna be able to delet the old version to save space but since when the docker is running and we stop em we cant delet it without restarting the docker service befor so we automated a bit of this part and share it since its usefull for any one who seriously runns docker in production or countinules development

Little stuff out of DirektSPEED Docker Managers - deployment script:

Update a Already Running Docker Container

Save ID of Current running Dockercontainer Version into a var
-> Build new container
-> Tag new container as an image and name it
-> Stop old running container using its IDS
-> Restart docker service
-> Run new container in daemon-mode based on newly built image
-> Delete old stopped containers
-> Delete old un-tagged images

Here is the full bash script which does the above:

#!/usr/bin/env bash
set -e

echo '>>> Get old container id'
CID=$(sudo docker ps | grep "project" | awk '{print $1}')
echo $CID

echo '>>> Building new image'
# analyse the log to find out if build passed (see https://github.com/dotcloud/docker/issues/1875)
sudo docker build ./deploy | tee /tmp/docker_build_result.log
RESULT=$(cat /tmp/docker_build_result.log | tail -n 1)
if [[ "$RESULT" != *Successfully* ]];
then
  exit -1
fi

echo '>>> Tagging new image'
NEW=$(sudo docker ps -a -q | head -n 1)
sudo docker commit $NEW project


echo '>>> Stopping old container'
if [ "$CID" != "" ];
then
  sudo docker stop $CID
fi


echo '>>> Restarting docker'
sudo service docker restart
sleep 5


echo '>>> Starting new container'
sudo docker run -p 3000:80 -d project /usr/bin/supervisord --nodaemon


echo '>>> Cleaning up containers'
sudo docker ps -a | grep "Exit" | awk '{print $1}' | while read -r id ; do
  sudo docker rm $id
done


echo '>>> Cleaning up images'
sudo docker images | grep "^<none>" | head -n 1 | awk 'BEGIN { FS = "[ \t]+" } { print $3 }'  | while read -r id ; do
  sudo docker rmi $id
done
Say Thanks
Respond

1 Response
Add your response

15344
330a6060531f963c33041c43e7356484

is there a specific reaseon, why your restart the docker service (and stop all other running containers) prior the start of the newly builded image?

over 1 year ago ·
Filed Under