简体   繁体   中英

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. I would have usually done this from my local machine, but via the docker container it gives me an error:

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

If you want to access your host's Docker service from inside a container, you need to map the Docker socket into the container. 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>]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM