[英]Docker py how to access from a container the Docker Host with from_env()
I am inside a container and I'd like to grab a container from the Docker machine/host.我在一个容器内,我想从 Docker 机器/主机中获取一个容器。 I would have usually done this from my local machine, but via the docker container it gives me an error:我通常会在我的本地机器上完成此操作,但通过 docker 容器它会给我一个错误:
client = docker.from_env()
client.containers.get('myPostgres')
Spits out:吐出来:
AttributeError: 'function' object has no attribute 'get'
A container by default will not have any access to the host Docker service (this is a security feature: access to docker is synonymous with root
access, so you only want to expose this access in specific situations).默认情况下,容器将无权访问主机 Docker 服务(这是一项安全功能:访问 docker 等同于root
访问权限,因此您只想在特定情况下公开此访问权限)。
If you want to access your host's Docker service from inside a container, you need to map the Docker socket into the container.如果要从容器内部访问主机的 Docker 服务,则需要将 map 和 Docker 套接字插入容器。 Generally, this means running something like:通常,这意味着运行如下内容:
docker run -v /var/run/docker.sock:/var/run/docker.sock ...
Compare:相比:
$ docker run --rm -it docker.io/python:3.10 bash
$ pip install docker
[...]
$ python
root@2dfed359374e:/# python
Python 3.10.3 (main, Mar 18 2022, 16:01:59) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import docker
>>> c = docker.from_env()
Traceback (most recent call last):
[...]
FileNotFoundError: [Errno 2] No such file or directory
With this:有了这个:
$ docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock docker.io/python:3.10 bash
root@ebe430bc9463:/# pip install docker
[...]
root@ebe430bc9463:/# python
Python 3.10.3 (main, Mar 18 2022, 16:01:59) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import docker
>>> c = docker.from_env()
>>> c.containers.list()
[<Container: ebe430bc94>, <Container: 91f24628fd>]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.