Play with Docker Engine API using Python

In this post, I manage to cover some basic knowledge and usage of Docker Engine API. Take advantage of API can sometimes make your life happier. ✌️

Preconditions

  1. You have the latest Docker installed.
  2. Python 2 or Python 3. (I recommend to Python 2 for later instructions)

Basic knowledge

The Engine API is an HTTP API served by Docker Engine. It is the API the Docker client uses to communicate with the Engine, so everything the Docker client can do can be done with the API.
Most of the client’s commands map directly to API endpoints (e.g. docker ps is GET /containers/json). The notable exception is running containers, which consists of several API calls.

Basic Usage

You can operate with either curl, like:

$ curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -X GET "http:/v1.26/containers/json" # docker ps

Or SDKs, such as docker (Python) .

From now on, when we mention docker , it means the SDK for python, and Docker represents the Docker Engine instead. We will mainly focus on docker in the following context.

docker (version 2 series)

If you are familiar with Python , it will be very easy for you to get started with docker. If not, I suggest you start to learn some basics to ensure you know what is happening and how to manipulate those commands later.

Following is a working example for docker ps :

You can manipulate almost every commands Docker provides with docker, and docker also provides higher API for you. Check out the example below, for instance, the same docker ps command invoked by docker higher API:

Advanced Usage

Think about doing a big project, which involves lots of Docker commands. It will absolutely impede your progress while you develop with SDKs. Lots of arguments and types you will have to pay attention, and even a simple docker run can lead you in the suds.

Therefore, I’ve created tsaotun, a Python based Assistance for Docker, to make my life happier, and yours too. 🏄

Tsaotun — Python based Assistance for Docker

Compared to docker, tsaotun has almost the same experience with Docker :

And even more:

You can check it out here for more details and document: https://github.com/qazbnm456/tsaotun

Conclusion

Many people would consider using exec or system to access Docker commands, and indeed it’s the most convenient way for a beginner. In practice, however, utilize API can actually make cross platform applications work well like it should, and no unexpected surprise for end users.

Besides, the version of Engine API with the latest Docker CE is 1.32, and it has exposed more and more new commands Docker introduced.

Therefore, it’s okay accessing Docker directly with the shell if you develop a small project, but I’d recommend utilizing API fully with larger projects.

Like what you read? Give Boik a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.