Following the line of the previous post () in this one I will show another piece of code, which will also be very useful in the next posts. How to execute a Shell command in an already running Container. https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.Container.exec_run

In the example below, I use the file that was uploaded in the previous post to change ownership to jenkins:jenkins (chown). The command that will be executed doesn’t matter, it can be anything and you will see that I must use this several times in the future.

Continuing, I will run the “chown” command and pass ownership to “jenkins:jenkins” of the file “devops-db.info” in the container “srv-jenkins-01” on the Docker server “172.21.5.70“.

In this case, I need the command to be executed with privileges, so the bol_Privileged flag and the user str_User, if not necessary, could, for example, run as bol_Privileged = False and “str_User = ‘jenkins'”, whatever you need.

Before execution:

root@b31bd131e02f:/tmp# ls -lah
total 30M
drwxrwxrwt 1 root    root    4.0K May  7 13:09 .
drwxr-xr-x 1 root    root    4.0K May  7 13:09 ..
-rw-r--r-- 1     502 dialout  517 Apr 29 15:43 devops-db.info

Then I run the Python below:

import docker

str_Docker_URI = 'tcp://172.21.5.70:2375'
str_Container_Name = 'srv-jenkins-01'
str_Command = 'chown jenkins:jenkins /tmp/devops-db.info'
bol_Privileged = True
str_User = 'root'

obj_DockerClient = docker.DockerClient(base_url=str_Docker_URI)
obj_Container = obj_DockerClient.containers.get(str_Container_Name)

obj_Return = obj_Container.exec_run(str_Command, privileged=bol_Privileged, user=str_User)

print(obj_Return)

The result:

root@b31bd131e02f:/tmp# ls -lah
total 30M
drwxrwxrwt 1 root    root    4.0K May  7 13:09 .
drwxr-xr-x 1 root    root    4.0K May  7 13:09 ..
-rw-r--r-- 1 jenkins jenkins  517 Apr 29 15:43 devops-db.info