Bash parse docker status to check if local image is up to date

杀马特。学长 韩版系。学妹 提交于 2020-01-04 02:19:10

问题


I have a starting docker script here:

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

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


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


echo '>>> Starting new container'
sudo docker pull my-example-registry.com:5050/web-client:latest
sudo docker run --name=web-client -p 8080:80 -d my-example-registry.com:5050/web-client:latest

The fact is this script has umproper result. It deletes the old container everytime the script is run.

The "starting new container" section will pull the most recent image. Here is an example output of docker pull if the image locally is up to date:

Status: Image is up to date for my-example-registry:5050/web-client:latest

Is there any way to improve my script by adding a condition:

Before anything, check via docker pull the local image is the most recent version available on registry. Then if it's the most recent version, proceed the stop and delete old container action and docker run the new pulled image.

In this script, how to parse the status to check the local image corresponds to the most up to date available on registry?

Maybe a docker command can do the trick, but I didn't manage to find a useful one.


回答1:


Check the string "Image is up to date" to know whether the local image was updated:

sudo docker pull my-example-registry.com:5050/web-client:latest | 
   grep "Image is up to date" ||
   (echo Already up to date. Exiting... && exit 0)

So change your script to:

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

sudo docker pull my-example-registry.com:5050/web-client:latest | 
   grep "Image is up to date" ||
   (echo Already up to date. Exiting... && exit 0)


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


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


echo '>>> Starting new container'
sudo docker run --name=web-client -p 8080:80 -d my-example-registry.com:5050/web-client:latest



回答2:


Simple use docker-compose and you can remove all the above.

docker-compose pull && docker-compose up

This will pull the image, if it exists, and up will only recreate the container, if it actually has a newer image, otherwise it will do nothing



来源:https://stackoverflow.com/questions/44739538/bash-parse-docker-status-to-check-if-local-image-is-up-to-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!