Kri*_*czi 8 bash shell curl docker docker-api
我想捕获 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
Run Code Online (Sandbox Code Playgroud)
但是有没有办法连续监听并处理每一行/事件?例如:
while EVENT ?magic?; do
ACTION=$(echo $EVENT | jq .Action )
if [ $ACTION -eq "start" ]; then ....; fi
done
Run Code Online (Sandbox Code Playgroud)
解决方案
@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;
Run Code Online (Sandbox Code Playgroud)
您可以尝试docker events
连续控制台docker事件。
docker events
Run Code Online (Sandbox Code Playgroud)
例如,如果您只对 grep container started
event 感兴趣,则以下命令将起作用,或者您可以改进以下脚本。
#!/bin/bash
docker events | while read line; do if [[ ${line} = *"start"* ]];then echo " container started ${line}" ;fi ; done
Run Code Online (Sandbox Code Playgroud)