pythondockerdockerpy

How to get the sub directories of docker mounts using python


I'm trying to do automation. For that, I need to check whether the children of the source directory in host system are equal to children directory in the destination directory of the container.

docker inspect -f '{{ .Mounts }}' devtest 
[{bind  /home/usr/location/docker/myapp/target /app   true rprivate}]

From the above code /home/usr/location/docker/myapp/target is the source from the host and similarly the /app is the destination where the mount is binded.

So as per my requirement I need to find the count of sub directory in both the source and destination. In the case of source is calculated using os.walk. But I have no idea about how to find it from the container using python.

I'm using docker-py module as utility for docker. May I know how can I achieve this using python


Solution

  • You can use docker exec on the docker host machine and then use the Linux ls command along with wc to find the directory count.

    You can use either the os or subprocess python modules to run the command. (subprocess is the pythons recommended option).

    import os
    
    os.system("docker exec <container-id/name> ls /app |wc -l")
    

    You can use -d option in the command, if you want to run it as a daemon.