Docker Engine exposes the REST API that you can use to control your containers without docker
CLI. The API exposes equivalent functionality using HTTP network calls. You can script common Docker operations using your favorite programming language or remotely manage one of your hosts. The CLI relies internally on the same API to provide its built-in commands.
In this article, we will look at the basics of enabling and using the API. If you have a specific use case in mind, refer to the API reference documentation to identify the endpoints you need.
Enabling the Docker Engine API
The API is integrated with the Docker Engine. Each functional Docker host is already prepared to provide API interaction services. To discover the service, you need to connect the Docker daemon to the TCP socket as, or instead of, the default Unix socket. Get started dockerd
with -H
flag for determining sockets for listening:
sudo dockerd -H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375
This command detects the API on port 2375. The default Unix socket is retained so that the Docker CLI will continue to function without any reconfiguration. Port 2375 is used for Docker by convention; feel free to change it to suit your environment.
You can make Docker always start with these settings by editing them systemd
service configuration file. Edit or create /etc/systemd/system/docker.service.d/options.conf
find ExecStart
line and modify it to include your additional flags:
[Service] ExecStart=/usr/bin/dockerd -H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375
Reload yours systemd
configuration for applying change:
sudo systemctl daemon-reload
You are now ready to interact with the included Docker Engine API 127.0.0.1:2375
.
Safety notice
The above steps reveal the API without any protection. Anyone with access to port 2375 on your host can send arbitrary commands to the Docker daemon, launch new containers, fill your disk with images, or destroy existing workloads.
You should set up your firewall to block port connections unless you intentionally expose Docker to your network. If you want to enable remote access, you should configure the TLS for the socket daemon to restrict access to authenticated clients.
Once TLS is enabled, you will need to install your daemon certificate authority on each of your clients. You will be required to provide a client certificate and client key with each request you make. The steps to take will depend on the tool you are using. Here is an example for curl
:
curl https://127.0.0.1:2375/v1.41/containers/json --cert client-cert.pem --key client-key.pem
You may not need to connect a TCP socket, depending on your use case. If your client supports Unix sockets, you can use Docker’s existing one to connect:
curl --unix-socket /var/run/docker.sock http://localhost/v1.41/containers
This may be a safer choice than the risk of inadvertent exposure of the TCP socket.
Using the API
The API uses versioned endpoints so you can hook up to specific versions of request and response formats. You must specify the version you use at the beginning of each endpoint URL. v1.41 is the latest release present in production Docker versions at the time of writing.
http://127.0.0.1:2375/v1.41
API endpoints are grouped into REST functional units. These are mapped to Docker’s basic object types such as containers, images, and volumes. You can usually find APIs for a particular object type within a base URL that begins with its name:
# APIs related to container operations http://127.0.0.1:2375/v1.41/containers
The API uses JSON for all data exchanges with your HTTP client. The endpoints accept the JSON request bodies and in turn issue JSON responses. This should simplify the handling of data within your applications because you can use the JSON library included in your programming environment. Tools like jq
it can be used to condense, filter, and sort responses if you experiment in your terminal.
Common endpoints
As the API replicates the functionality of Docker’s CLI, there are too many possible endpoints to cover them all here. Instead, we’ll demonstrate a few of the most commonly used options related to Docker’s basic functionality.
Listing Containers
You can get a complete list of containers on the host from /containers/json
end point:
curl http://127.0.0.1:2375/v1.41/containers/json
By default, only running containers are displayed. Add all=true
to include stopped containers in the query string. Limit the total number of containers returned from limit
parameter, such as limit=10
. Only 10 recently created containers will be included.
Several different filters are available to reduce the list to containers with certain attributes. They are set with the following syntax:
curl http://127.0.0.1:2375/v1.41/containers/json?filters={"name":"demo"}
This URL returns information related to demo
container. Other filters can be expressed in a similar way as e.g. {"status":["running","paused"]}
to start and pause the container or {"health=["healthy"]}
only for healthy containers.
Launch a new container
Launching a container is a two-phase process when using the API. You must first create a container and then run it in a separate API call.
Create your own container by making a POST
request for /containers/create
end point. This requires a JSON body with fields corresponding to the labels it accepts docker run
CLI command.
Here is a minimal example of creating a container:
curl http://127.0.0.1:2375/v1.41/containers/create -X POST -H "Content-Type: application/json" -d '{"Image": "example-image:latest"}'
The JSON response will include the ID of the new container and any alerts arising from its creation. Send the ID in the invitation to /containers/:id/start
end point:
curl http://127.0.0.1:2375/v1.41/containers/abc123/start -X POST
The container will now work on the Docker host.
Container cleaning
Remove stopped containers by issuing a POST
request for /containers/prune
end point:
curl http://127.0.0.1:2375/v1.41/containers/prune -X POST
You will get a JSON answer with ContainersDeleted
i SpaceReclaimed
fields. ContainersDeleted
is a series of container IDs that have been successfully removed. SpaceReclaimed
notifies you of the total free memory space in bytes.
This endpoint accepts two query string parameters to constrain the operation. The until
the parameter limits deletion to containers created before a certain time, such as until=10m
or until=2022-03-01
. The label
container filter option with or without labels; setting up label=demo=example
will only remove containers with demo=example
label.
Listing Images
The /images/json
the endpoint is used to enumerate images stored on the Docker host:
curl http://127.0.0.1:2375/v1.41/images/json
You can use filters to change the content of the response. They are delivered as a JSON object in filters
query string parameter, similar to the container list API. One option worth noting is reference
who selects the image with the given tag: filters={"reference":"hello-world:latest"}
.
Building Images
You can use the API to create new Docker images from Dockerfiles. The /build
the endpoint should be sent a tar
archive. The content of this archive will be used as a context for creating the image. The archive should include a Dockerfile containing construction instructions.
cat context.tar | curl http://127.0.0.1:2375/v1.41/build?t=example-image:latest -X POST
The command above will send context.tar
on the Docker daemon and build an image using Dockerfile
inside. The image will be marked as example-image:latest
and stored on the Docker host.
This endpoint accepts many additional query string parameters that match the functionality docker build
CLI. That includes dockerfile=path/to/dockerfile
to specify the path to the Dockerfile construction context, rm=true
which erases the inter-containers created by construction, and pull=true
to try to get updated versions of the images referenced by Dockerfile.
The API requires that your client stay connected until construction is complete. Construction will be canceled if the network falls and the connection is closed.
Quoting the Daemon event log
The /events
The API displays daemon event log data that is also available with docker events
CLI command. This endpoint transmits real-time events as they occur.
curl http://127.0.0.1:2375/v1.41/events
Several different types of events are on display, including container creation, image tagging, volume editing, and network changes. You can filter on a specific type of event using type
field filters
query parameter:
# Only get container events curl http://127.0.0.1:2375/v1.41/events?filters={'type':'container'}
It is also possible to limit to object-specific events:
# Get events pertaining to the container with ID abc123 curl http://127.0.0.1:2375/v1.41/events?filters={'container':'id'}
Two other query string parameters, since
i until
allows you to specify a timestamp range to display historical events within.
Obtaining system information
The Docker Engine API can be used to obtain information about the physical host it is working on:
curl http://127.0.0.1:2375/v1.41/info
This endpoint provides extensive details describing the current state and configuration of the host and Docker daemon. Response fields include counting the number of started, paused, and stopped containers, the path to the Docker installation directory, hardware and OS details, and the configuration of the Swarm server when running within the cluster.
Conclusion
The Docker Engine API gives you a way to send Docker daemon commands to your host over HTTP. This makes it easier to script program interactions without relying on specific Docker CLI behaviors. The API can also be used to remotely manage your Docker servers for improved monitoring and maintenance.
Although calling the API should be easy, you need to pay attention to the security protections around your TCP socket. Avoid exposing the socket on your network unless it is protected by TLS so that only approved customers can connect. Omitting this additional setup phase could prove costly if an intruder detects your demonic instance and starts issuing orders.
You can make it even easier to use the API within your own applications by adopting one of the SDKs. For all popular programming languages, including C, C #, C ++, Go, Java, NodeJS, PHP, Python, and Ruby, the official or community-based option is available. SDKs wrap API endpoints in convenient classes and calling functions from your code, reducing the amount of templates needed to interact with the Docker installation.