首页 > 解决方案 > 在 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;

标签: bashshelldockercurldocker-api

解决方案


您可以尝试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

推荐阅读