I want to use docker sdk inside a running docker container and want to build an docker image inside running docker container and deploy it in minikube

2/4/2020
def list_img():
    client = docker.from_env()
    k=1
    img_list = client.images.list()
    for img in img_list:
        print(k," ",img)
        k+=1
    return "Images are listed successfully "

I want to list all the docker images using the python3 docker sdk inside a runing docker container deployed in minikube.

import docker 
def list_img():
    client = docker.from_env()
    k=1
    img_list = client.images.list()
    for img in img_list:
        print(k," ",img)
        k+=1
list_img()

Dockerfile

FROM python:3.6-slim
RUN apt upgrade
RUN apt update
RUN pip3 install flask
# RUN pip3 install kubernetes
RUN pip3 install docker

WORKDIR  /dckr_sdk
COPY  . /dckr_sdk

EXPOSE  5022
CMD [ "python3","flask4_bld_dckr_img.py" ]

And I am getting the below error

File "/usr/local/lib/python3.6/site-packages/docker/transport/unixconn.py", line 43, in connect
    sock.connect(self.unix_socket)
urllib3.exceptions.ProtocolError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))

File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 498, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
-- Rahees Khan
docker
kubernetes
minikube

1 Answer

2/4/2020

Using docker in a docker container can be done in 2 ways:

  1. Using the docker deamon of the host machine.
  2. Really installing and using docker within another docker.

Method 2 is generally not what you want to do as it has a lot of unwanted side effects. For method 1 you need to:

  1. Install the docker-cli in your image, add this to your Dockerfile or adapt it to the base image you are using:
# Install docker
RUN apt-get update
RUN apt-get -y install apt-transport-https ca-certificates curl gnupg2 software-properties-common
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
  1. When running the docker container, you need to mount your host machine's docker deamon socket:
docker run -v /var/run/docker.sock:/var/run/docker.sock docker-image-name

This should do the trick and enable you to use the python docker sdk in your own container. More on docker-in-docker here: https://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/

-- Sander Vanhove
Source: StackOverflow