8

I would like to catch docker events and do something if something is happend. There are lots of ways to "get/print events":

# With curl
curl --unix-socket /var/run/docker.sock http:/v1.40/events

# With nc
echo -e "GET /events HTTP/1.0\r\n" | nc -U /var/run/docker.sock

But is there any way to listen continously and handle each row/event? Eg:

while EVENT ?magic?; do
    ACTION=$(echo $EVENT | jq .Action )
    if [ $ACTION -eq "start" ]; then ....; fi
done

Solution

After @Adiii answer, a short solution:

#!/bin/bash

function handle {
    # Check the line is a JSON line:
    if [[ ${1:0:1} == "{" ]]; then

        # ... You can do here anything ...

        # Print: "LOG $line", "LOG" is green
        echo -e "\033[32;1mLOG\033[0m $line"
    fi
}

echo -e "GET /events HTTP/1.0\r\n" | nc -U /var/run/docker.sock | while read line; do handle $line; done;

1 Answers1

6

You can try docker events which continuously console docker event.

docker events 

For example if you just interested to grep container started event the below command will work, or you can improve the below script.

#!/bin/bash
docker events |  while read line; do  if [[ ${line} = *"start"* ]];then echo " container started ${line}" ;fi ; done
Adiii
  • 54,482
  • 7
  • 145
  • 148