How to Get Started Using the Docker Engine API

Docker Engine exposes a REST API which you need to use to regulate your containers with out the docker CLI. The API exposes equal performance utilizing HTTP community calls. You may script widespread Docker operations utilizing your favourite programming language or remotely management certainly one of your hosts. The CLI internally depends on the identical API to offer its built-in instructions.

On this article we’ll have a look at the fundamentals of enabling and utilizing the API. For those who’ve acquired a particular use case in thoughts, consult with the API reference documentation to establish the endpoints you want.

Enabling Docker Engine’s API

The API is built-in with Docker Engine. Any functioning Docker host is already primed to cater for API interactions. To reveal the service, it’s good to bind the Docker daemon to a TCP socket in addition to, or as a substitute of, the default Unix socket. Begin dockerd with the -H flag to specify the sockets to hear on:

sudo dockerd -H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375

This command exposes the API on port 2375. The default Unix socket is retained so the Docker CLI will proceed functioning with none reconfiguration. Port 2375 is used for Docker by conference; be happy to alter it to fit your atmosphere.

You may make Docker all the time begin with these settings by modifying its systemd service configuration file. Edit or create /and many others/systemd/system/docker.service.d/choices.conf, discover the ExecStart line, and modify it to incorporate your further flags:

[Service]
ExecStart=/usr/bin/dockerd -H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375

Reload your systemd configuration to use the change:

sudo systemctl daemon-reload

Now you’re able to work together with the Docker Engine API on 127.0.0.1:2375.

A Word On Safety

The steps above expose the API with no safety in any respect. Anybody with entry to port 2375 in your host can ship arbitrary instructions to the Docker daemon, beginning new containers, filling your disk with photographs, or destroying present workloads.

You must set your firewall to dam connections to the port until you’re deliberately exposing Docker in your community. For those who do wish to allow distant entry, you need to configure TLS for the daemon socket to restrict entry to authenticated shoppers.

When TLS is enabled you’ll want to put in your daemon’s certificates authority on every of your shoppers. You’ll have to produce the shopper certificates and shopper key with every request you make. The steps to take will depend upon the software you’re utilizing. Right here’s an instance for curl:

curl https://127.0.0.1:2375/v1.41/containers/json --cert client-cert.pem --key client-key.pem

You may not must bind a TCP socket in any respect relying in your use case. In case your shopper helps Unix sockets, you possibly can use Docker’s present one to make your connections:

curl --unix-socket /var/run/docker.sock http://localhost/v1.41/containers

This is usually a safer alternative than risking unintentional publicity of a TCP socket.

Utilizing the API

The API uses versioned endpoints so you’ll be able to pin to particular variations of request and response codecs. It’s essential to point out the model you’re utilizing initially of every endpoint URL. v1.41 is the newest launch current in manufacturing Docker builds on the time of writing.

http://127.0.0.1:2375/v1.41

API endpoints are grouped into REST useful models. These map to Docker’s elementary object sorts resembling containers, photographs, and volumes. You may often discover the APIs for a particular object kind throughout the base URL that begins with its title:

# APIs associated to container operations
http://127.0.0.1:2375/v1.41/containers

The API makes use of JSON for all information exchanges along with your HTTP shopper. Endpoints settle for JSON request our bodies and subject JSON responses in return. This could simplify information dealing with inside your functions as you need to use the JSON library included along with your programming atmosphere. Instruments like jq can be utilized to condense, filter, and kind responses in case you’re experimenting in your terminal.

Widespread Endpoints

Because the API replicates the performance of Docker’s CLI, there’s too many doable endpoints to cowl all of them right here. As a substitute we’ll exhibit a number of of essentially the most generally used choices referring to Docker’s core performance.

Itemizing Containers

The whole record of containers on the host will be obtained from the /containers/json endpoint:

curl http://127.0.0.1:2375/v1.41/containers/json

It defaults to surfacing solely operating containers. Add all=true to the question string to incorporate stopped containers too. Restrict the overall variety of containers returned with the restrict parameter, resembling restrict=10. Solely the ten most recently-created containers will likely be included.

A number of different filters can be found to prune the record to containers with specific attributes. These are set with the next syntax:

curl http://127.0.0.1:2375/v1.41/containers/json?filters="title":"demo"

This URL returns the knowledge related to the demo container. Different filters will be expressed in an identical method resembling "standing":["running","paused"] to get operating and paused containers or for less than wholesome containers.

Beginning a New Container

Beginning a container is a two-stage course of when utilizing the API. First it’s good to create the container, then begin it in a separate API name.

Create your container by making a POST request to the /containers/create endpoint. This wants a JSON physique with fields that correspond to the flags accepted by the docker run CLI command.

Right here’s a minimal instance of making a container:

curl http://127.0.0.1:2375/v1.41/containers/create 
    -X POST 
    -H "Content material-Sort: software/json" 
    -d '"Picture": "example-image:newest"'

The JSON response will embrace the brand new container’s ID and any warnings arising from its creation. Ship the ID in a name to the /containers/:id/begin endpoint:

curl http://127.0.0.1:2375/v1.41/containers/abc123/begin -X POST

The container will now be operating on the Docker host.

Cleansing Up Containers

Take away stopped containers by issuing a POST request to the /containers/prune endpoint:

curl http://127.0.0.1:2375/v1.41/containers/prune -X POST

You’ll be issued a JSON response with ContainersDeleted and SpaceReclaimed fields. ContainersDeleted is an array of the container IDs that had been efficiently eliminated. SpaceReclaimed informs of you the overall cupboard space freed in bytes.

This endpoint accepts two question string parameters to constrain the operation. The till parameter limits the deletion to containers created earlier than a given time, resembling till=10m or till=2022-03-01. The label choice filters to containers with or with out given labels; setting label=demo=instance will solely take away containers with the demo=instance label.

Itemizing Photos

The /photographs/json endpoint is used to enumerate the photographs saved on the Docker host:

curl http://127.0.0.1:2375/v1.41/photographs/json

You should utilize filters to change the contents of the response. These are equipped as a JSON object within the filters question string parameter, equally to the container record API. One noteworthy choice is reference which selects the picture with a given tag: filters=.

Constructing Photos

You should utilize the API to construct new Docker photographs from Dockerfiles. The /construct endpoint ought to be despatched a tar archive. The contents of this archive will likely be used because the picture’s construct context. The archive ought to embrace Dockerfile containg the directions for the construct.

cat context.tar | curl http://127.0.0.1:2375/v1.41/construct?t=example-image:newest -X POST

The command above will ship context.tar to the Docker daemon and construct a picture utilizing the Dockerfile inside. The picture will likely be tagged as example-image:newest and saved on the Docker host.

This endpoint accepts many extra question string parameters that match the performance of the docker construct CLI. These embrace dockerfile=path/to/dockerfile, to specify the trail to the construct context’s Dockerfile, rm=true, which deletes intermediate containers created by the construct, and pull=true to attempt to purchase up to date variations of photographs referenced by the Dockerfile.

The API requires your shopper keep related till the construct completes. The construct will likely be cancelled if the community drops and the connection is closed.

Itemizing Daemon Occasion Logs

The /occasions API surfaces the daemon occasion log information that’s additionally accessible with the docker occasions CLI command. This endpoint streams occasions in real-time as they occur.

curl http://127.0.0.1:2375/v1.41/occasions

A number of totally different sorts of occasion are uncovered together with container creations, picture tags, quantity mounts, and community modifications. You may filter to a particular sort of occasion utilizing the kind area of the filters question parameter:

# Solely get container occasions
curl http://127.0.0.1:2375/v1.41/occasions?filters=

It’s additionally doable to constrain to occasions referring to a particular object:

# Get occasions pertaining to the container with ID abc123
curl http://127.0.0.1:2375/v1.41/occasions?filters={'container':'id'}

Two different question string parameters, since and till, allow you to specify a timestamp vary to floor historic occasions inside.

Getting System Data

The Docker Engine API can be utilized to get details about the bodily host it’s operating on:

curl http://127.0.0.1:2375/v1.41/data

This endpoint supplies intensive particulars describing the present state and configuration of the host and Docker daemon. Fields within the response embrace counts of the variety of operating, paused, and stopped containers, the trail to Docker’s set up listing, {hardware} and OS particulars, and the server’s Swarm configuration when it’s working inside a cluster.

Conclusion

The Docker Engine API provides you a technique to ship instructions to your host’s Docker daemon over HTTP. This makes it less complicated to script programmatic interactions with out turning into reliant on particular Docker CLI behaviors. The API can be used to remotely handle your Docker servers for enhanced monitoring and ease of upkeep.

Whereas calling the API ought to be easy, it’s good to take note of the safety protections round your TCP socket. Keep away from exposing the socket in your community until it’s secured with TLS so solely accepted shoppers can join. Omitting this further arrange stage may show pricey if an intruder discovers your daemon occasion and begins issuing instructions.

You may make it even simpler to make use of the API inside your personal functions by adopting one of the SDKs. Both an official or community-provided choice is offered for all common programming languages, together with C, C#, C++, Go, Java, NodeJS, PHP, Python, and Ruby. The SDKs wrap the API’s endpoints in handy lessons and features to name out of your code, lowering the quantity of boilerplate wanted to work together with a Docker set up.

Leave a Reply

Your email address will not be published. Required fields are marked *