Issue
What is the most optimal way for a process on a Linux PC to get informed automatically when a new Docker container is created ?
I know it is possible to check the date with Docker Engine API, but there is maybe a better solution, with file watchers or something like that ?
Solution
$ docker events --filter "type=container" --filter "event=create" --format "{{json .}}" | jq -r
will listen all docker events in real time and print only container create
events like:
{
"status": "create",
"id": "0d4f9f...f072c1e305",
"from": "hello-world",
"Type": "container",
"Action": "create",
"Actor": {
"ID": "0d4f9f9b8b20...7f072c1e305",
"Attributes": {
"desktop.docker.io/wsl-distro": "Debian",
"image": "hello-world",
"name": "lucid_engelbart"
}
},
"scope": "local",
"time": 1667446412,
"timeNano": 1667446412029074700
}
Also, you may set dates:
$ docker events --since $(date "+%s" -d "-1 day") --until $(date "+%s") --filter "type=container" --filter "event=create" --format "{{json .}}" | jq -r
will print all events for one day.
Also, it is possible to use curl
to get info via REST API:
$ curl -H "Content-Type: application/json" --unix-socket /var/run/docker.sock "http://localhost/events?since=$(date "+%s" -d "-1 day")&until=$(date "+%s")&filters=%7B%22event%22%3A%7B%22create%22%3Atrue%7D%2C%22type%22%3A%7B%22container%22%3Atrue%7D%7D" | jq
Docker is listening to Unix socket by default so --unix-socket
parameter is needed. However, it is possible to connect to Docker via TCP socket, but you have to change Docker Engine parameters (Not sure but probably web socket may be used in this case?).
Also, if you set until
parameter (CLI and curl
the same) Docker will print all events until
date and exit without continuous listening for new ones.
Of course, Docker libraries and SDKs may be used to get same output programmatically, but it depends on programming language, so it is hard to provide exact example
*pipelined jq
is not necessary in real usage. I just added it for pretty printing.
PS. Thanks to @David Maze for the comment. Didn't know about this feature before
Answered By - rzlvmp Answer Checked By - Mary Flores (WPSolving Volunteer)