Access the Docker Engine API from inside a Docker Container

01-08-2020


If you’re using Docker and need to access to Docker Engine API, Docker makes it really easy to do. For example, let’s say you’re inside of a container and you need to query the API to find out what other containers are running that you might need to communicate with. To gain access to the Docker Engine API we just need to mount an additional volume to get access to the socket connection.

Start a container:

1
docker run -it --rm -v /var/run/docker.sock:/var/run/docker.sock node bash

The -v /var/run/docker.sock:/var/run/docker.sock portion of the docker run command gives us access to the socket and ultimately to the Docker Engine’s API. Once inside the container we can then query the API for any information we need.

Example cURL query to get container information:

1
curl --unix-socket /var/run/docker.sock http://v1.30/containers/json

The host we’re querying is http://v1.30/containers/json. This will give us the same results as if we ran docker ps in our terminal (outside of a container, on the host). The API gives us access to many if not all of the Docker commands we know and love.