Accessing host machines docker daemon from a container!!!

Kumar Pavan
2 min readFeb 16, 2021

Sometimes we have to do it however impossible the task seems to be, but since there is an awesome dev community out there the impossible becomes easy, so long story short I had a situation where I had to use docker inside my docker container and I am going to tell you exactly how I did it.

Understanding what we want

understanding how we are accessing docker in a container

Lets simply understand what we are trying to do and why we are doing it this way:

  1. We need docker installed to access docker daemon and access various docker commands.
  2. Since docker is already installed on host we are binding the same volume to our container.
  3. We also need the docker-cli to execute docker commands.

Dockerfile

Commands to build and run the docker for demo and sample Dockerfile

I have taken base image as alpine, added docker-cli since we need docker commands to be recognised and an entry point where I am just running a docker command to print all containers, you can change the entry point to any docker command you wish or you can trigger a shell script that contains series of docker commands to be executed.

Finally the magic happens when you run the container by mounting the docker volume to container.

docker run -v /var/run/docker.sock:/var/run/docker.sock <container>

Conclusion

In the below image you can see terminal executing the commands and printing all the containers of docker on host machine.

Terminal image executing docker commands

CAUTION: Since you are binding to host docker volume any commands you run from inside container will have an effect on host volume.Example, say you try to delete/prune an image that you built in container we need to keep in mind that both container and host are sharing same docker volume.

--

--

Kumar Pavan

Mechanical Engineer by degree, a programmer by virtue of analysis, Web Developer by profession.