处理 shell 脚本中的 docker 事件
Handling docker events in shell script
我想捕捉 docker 事件并在发生某些事情时做一些事情。 "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
但是有什么方法可以连续监听并处理每个row/event?例如:
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 "3[32;1mLOG3[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;
您可以尝试 docker events
持续控制 docker 事件。
docker events
例如,如果您只是对 grep container started
事件感兴趣,下面的命令将起作用,或者您可以改进下面的脚本。
#!/bin/bash
docker events | while read line; do if [[ ${line} = *"start"* ]];then echo " container started ${line}" ;fi ; done
我想捕捉 docker 事件并在发生某些事情时做一些事情。 "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
但是有什么方法可以连续监听并处理每个row/event?例如:
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 "3[32;1mLOG3[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;
您可以尝试 docker events
持续控制 docker 事件。
docker events
例如,如果您只是对 grep container started
事件感兴趣,下面的命令将起作用,或者您可以改进下面的脚本。
#!/bin/bash
docker events | while read line; do if [[ ${line} = *"start"* ]];then echo " container started ${line}" ;fi ; done