我想在正在运行的docker容器中使用docker sdk,并想要在正在运行的docker容器中构建docker映像并将其部署在minikube中

时间:2020-02-04 09:32:48

标签: docker kubernetes minikube

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 "

我想在minikube中部署的正在运行的Docker容器中使用python3 docker sdk列出所有docker映像。

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" ]

我收到以下错误

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'))

1 个答案:

答案 0 :(得分:1)

在docker容器中使用docker可以通过两种方式完成:

  1. 使用主机的docker守护进程。
  2. 真正在另一个docker中安装和使用docker。

方法2通常不是您想要执行的,因为它有很多不良的副作用。对于方法1,您需要:

  1. 在映像中安装docker-cli,将其添加到Dockerfile或使其适应所使用的基本映像:
# 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. 运行docker容器时,您需要安装主机的docker deamon套接字:
docker run -v /var/run/docker.sock:/var/run/docker.sock docker-image-name

这应该可以解决问题,并使您能够在自己的容器中使用python docker sdk。有关docker-in-docker的更多信息,请访问:https://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/