我想要捕获docker事件,并在发生某些事情时采取一些行动。有许多方式可以“获取/打印事件”:
# 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
但是有没有一种方式可以连续监听并处理每一行/事件?例如:
while EVENT ?magic?; do
ACTION=$(echo $EVENT | jq .Action )
if [ $ACTION -eq "start" ]; then ....; fi
done
解决方案
在 @Adiii 的答案之后,这是一个简短的解决方案:
#!/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;