bash - 在 shell 脚本中处理 docker 事件
问题描述
我想捕捉 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;
解决方案
您可以尝试docker events
使用哪个连续控制台 docker 事件。
docker events
例如,如果您只是对 grepcontainer started
事件感兴趣,则以下命令将起作用,或者您可以改进以下脚本。
#!/bin/bash
docker events | while read line; do if [[ ${line} = *"start"* ]];then echo " container started ${line}" ;fi ; done
推荐阅读
- python - 如何让 python 在新的 cmd 中打开另一个 python 文件?
- c# - Automapper Aftermap“找不到方法”异常
- php - 有没有办法使用 Html、php 等获取当前的 Windows 登录用户名?
- c++ - 这是什么 `(*(T*)nullptr)` 老把戏?
- javascript - 如何折叠响应式导航栏
- python - 使用 strftime 更改为字符串时如何将 datetime.date 更改为 st,nd,rd,th
- awkward-array - Uproot 4中的TLorentz向量
- r - 在 rmd 子文件中嵌套不同的块
- mysql - Docker 内外不同的 MySQL 字符集
- vb.net - 应用 。启动路径不起作用 vb.net