Docker ps command into XARGS command to check and auto restart unhealthy containers

35 Views Asked by At

docker ps -f health=unhealthy --format "docker restart {{.ID}}" | xargs --no-run-if-empty -t docker restart

output is :

docker restart docker restart 7c20974e2b02

7c20974e2b02

Error response from daemon: No such container: docker

Error response from daemon: No such container: restart

How do I not get the "Error response from daemon: No such container: "

2

There are 2 best solutions below

0
Charles Duffy On

Take docker restart out of the format string; it should only be on the argument list.

docker ps -f health=unhealthy --format "{{.ID}}" |
  xargs --no-run-if-empty -t docker restart

When you had it in both places you were passing the string docker restart at least twice whenever xargs invoked anything at all.


Alternately, consider doing this without xargs entirely. Assuming that the number of unhealthy nodes is short enough to fit on a single command line -- generally a safe assumption, since the combined environment + argument length limit is typically in the range of 128KB on modern systems:

IFS=$'\n' read -r -d '' -a unhealthy_nodes < <(
  docker ps -f --health=unhealthy --format '{{.ID}}' && printf '\0'
) && (( ${#unhealthy_nodes[@]} )) &&
  docker restart "${unhealthy_nodes[@]}"
3
penguin359 On

You have both docker ps with its --format option and xargs putting docker restart in front of the container name. You need to do one or the other. Removing the format option will have docker ps only pass the container ID to xargs which will run it as an additional argument to docker restart that it already has:

docker ps -f health=unhealthy --format "{{.ID}}" | xargs --no-run-if-empty -t docker restart

Or you can remove restart from xargs and just have format add that by itself:

docker ps -f health=unhealthy --format "restart {{.ID}}" | xargs --no-run-if-empty -t docker

xargs always requires the base command so you can't pass docker in the format, but all other arguments can be fed into it. I'd recommend the former approach. This latter example is more to demonstrate the difference between each option. Also, if docker ps ever returns more than one ID, you only want restart to appear once as it will in the former case.