Darek's thoughts on IT solutions

"Docker-utils" - set of Bash and Python 2.7 scripts to handle Docker images and containers on basic CentOS box

07.01.2020

The first and the most important script is "start.py". Its aim is execute docker run ... command - first, you choose image from list of existing ones, and then you choose parameters from list - stored in plain text file "docker-run-params.txt", and at last you run the command. Here is start.py:

#!/usr/bin/python
#v0.07
"""
* comments lines in 'docker-run-params.txt' are displayed

* when container is run in non-detached mode, on container shell exit 'ExitCode' value returned form 'docker inspect ...' is checked
- it's purely decorative feature
"""

import subprocess, os, json
from datetime import datetime
"""
docker images --format '{{.Repository}}\t{{.ID}}\t{{.Tag}}'
"""
cmd = ["docker", "images", "--format",  "{{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}}\t{{.Size}}"]
cmdOutput = subprocess.check_output(cmd)
lImages = []
lImages = cmdOutput.split("\n")

RED='\033[0;31m'
GREEN='\033[0;32m'  
NC='\033[0m'

if (len(lImages)):
	for index in range(len(lImages)-1):
		lImages[index] = lImages[index].split("\t");
		print '%2i %-20s %-10s %-8s %-15s %10s' % (index + 1 , lImages[index][0] , lImages[index][1] , lImages[index][2], lImages[index][3], lImages[index][4]);
		#print lImages[index][0]

	msg = "choose 1-%i or q : " % (len(lImages) - 1)
	anwser = raw_input(msg)

	if (anwser == "q"):
		quit()
	else:
		#print lImages[int(anwser)][0]
		i = int(anwser) - 1
		now = datetime.now()
		date_time = now.strftime("%m%d%Y-%H%M%S")

		file = open("docker-run-params.txt", "r")
		rawlines = file.readlines()
		"""
			remove lines that starts with "#"
		"""
		lines = filter(lambda item: item.find("#", 0, 1) == -1, rawlines)
		lines = map(lambda item: item.rstrip(), lines)

		index2 = 0
		for index in range(len(rawlines)):
			if ("#" in rawlines[index]):
				print rawlines[index].rstrip()
			else:
				print index2 + 1, lines[index2]
				index2 = index2 + 1
		msg = "choose 1-%i or q : " % (len(lines))
		anwser = raw_input(msg)

		if (anwser == "q"):
			quit()
		else:
			i2 = int(anwser) - 1
			dockCmd = 'docker run %s' % (lines[i2].replace("<name>", "%s").replace("<repository>", "%s").replace("<tag>", "%s")) 
			dockCmd = dockCmd % (date_time, lImages[i][0], lImages[i][1])
			print dockCmd

			os.system(dockCmd)
			"""
			subprocess.check_output(["docker", "inspect", "-f", "{{.State.Running}}", "12122019-102612"])
			"""
			if (" -d " in dockCmd):
				# "-f", "{{json .State}}" - force to output JSON string
				cmdOutput = subprocess.check_output(["docker", "inspect", "-f", "{{json .State}}", "--type", "container", date_time])
				oJSON = json.loads(cmdOutput)
				if (oJSON['Running'] == False):
					print 'command:\n', dockCmd, RED, '\nfailed', NC
				else:
					print 'command:\n', dockCmd, GREEN, '\nsucceeded', NC
			else:
				p = subprocess.Popen(["docker", "inspect", "-f", "{{json .State}}", "--type", "container", date_time], stdout=subprocess.PIPE)
				cmdOutput = p.communicate()[0]
				oJSON = json.loads(cmdOutput)
				if (oJSON['ExitCode'] == 0):
					print 'command:\n', dockCmd, GREEN, '\nsucceeded', NC
				else:
					print 'command:\n', dockCmd, RED, '\nfailed', NC.

Example of docker-run-params.txt:

--privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 80:80 -d --name <name> <repository>:<tag> 
--privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro -d --name <name> <repository>:<tag> 
--privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 445:445 -d --name <name> <repository>:<tag> 
-it -p 3000:3000 --name <name> <repository>:<tag> bash
# '-p' multiple ports, '-w' user home directory
-it -p 3000:3000 -p 3001:3001 -u infor -w /home/infor --name <name> <repository>:<tag> bash 

docker-exec.sh is Bash script that runs docker exec ... command, it assumes that you have just one container running on your OS host, it will go to user’s home directory and start Bash session

#v0.03
id=`docker ps -q`
w=`docker version --format '{{json .}}'|jq '.Client.ApiVersion'|awk '{if ($1 > 1.35) print "--workdir";}'`
#docker exec -it $id /usr/bin/bash
if [ -z $w ]
then
#	docker exec -it $id sh -c "cd ~/ && /usr/bin/bash"
#	Debian/RasPi container case handled
	docker exec -it $id sh -c "cd ~/ && ([ -x "$(command -v /usr/bin/bash)" ] && /usr/bin/bash) || ([ -x "$(command -v /bin/bash)" ] && /bin/bash)"

else
	docker exec -w ~/ -it $id /usr/bin/bash
fi

Bash script docker-stop.sh stops container, notice you can replace stop with kill if you want it act more agressively

id=`docker ps -q`
docker stop $id