DEV Community

Max
Max

Posted on

Python Script to check if all docker containers are running

I created a small python script that checks if all docker containers are running.

  1. Backup all container names into a file: docker ps --format "{{.Names}}" > /root/containers.txt
  2. Create a script that checks if all containers are running: vim /root/check.py (Content see below)
  3. Do stuff that might impact container uptime
  4. Run the script: python3 /root/check.py
  5. See if every container are still running

Image description

=> Offline-Containers are highlighted in red.

Script Content:

#!/usr/bin/python3

import subprocess

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


f = open("/root/containers.txt", "r")
containers = f.read().splitlines()

docker_ps_output = str(subprocess.check_output('docker ps', shell=True))

for container in containers:
    if docker_ps_output.find(container) != -1:
       print(f"{bcolors.OKGREEN}Container found {container}{bcolors.ENDC}")
    else:
       print(f"{bcolors.FAIL}Container not found {container}{bcolors.ENDC}")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)