Advertisement
JLMoss

Restart Dockers

Aug 19th, 2023 (edited)
982
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.71 KB | Source Code | 0 0
  1. #!/bin/bash
  2. # function restartDockerByName()
  3. # requires a container name be passed to it
  4. function restartDockerByName(){
  5.     for j in $(docker container ls -a | grep $1 | cut -c1-12)
  6.     do
  7.         # this is a 'restart function'
  8.         # so make sure the docker is already running
  9.         # don't act on it otherwise
  10.         szStatus=`docker inspect -f '{{.State.Running}}' $j`
  11.         if [ "$szStatus" = "true" ]
  12.         then
  13.             #echo "$j state: Not Running"
  14.             echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: $1 is running"
  15.             echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: $1 stopping"
  16.             docker stop $j  > /dev/null 2>&1
  17.             echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: $1 stopped"
  18.             ##
  19.             echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: $1 starting"
  20.             docker start $j > /dev/null 2>&1
  21.             echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: $1 started"
  22.             echo ''
  23.         else
  24.             echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: $1 is not running"
  25.             echo ''        
  26.         fi
  27.        
  28.     done
  29. }
  30.  
  31. # szContainers: list of dockers to restart
  32. szContainers=('container1' 'container2');
  33. szCount=${#szContainers[@]};
  34.  
  35. # Check if docker is running
  36. if docker info > /dev/null 2>&1; then
  37.     echo ''
  38.     #echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: dockeris running"
  39.     #echo ''
  40.  
  41.     #loop thru szContainers
  42.     for i in ${szContainers[@]}; do
  43.         echo "Status: Restarting $i"
  44.         # restartDockerbyName <containername>
  45.         restartDockerByName $i
  46.     done
  47.  
  48.     echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: finished exiting"
  49. else
  50.     echo "`date "+%Y-%m-%d %H:%M:%S"`" "Status: docker is not running exiting"
  51.     exit 1
  52. fi
  53.  
  54. exit
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement