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'
CodePudding user response:
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>]