Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

docker

sh

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.

like image 763
BlackHoleGalaxy Avatar asked Jan 04 '23 19:01

BlackHoleGalaxy


2 Answers

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
like image 156
Robert Avatar answered Jan 06 '23 08:01

Robert


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

like image 41
Eugen Mayer Avatar answered Jan 06 '23 09:01

Eugen Mayer