Clear the container logs on Docker Desktop for Mac

This article is an introduction to clearing the container logs in Docker Desktop for Mac.
The version at the time of writing is Docker Desktop for Mac 3.2.2(61853).

About Docker Desktop for Mac

You can run docker inspect to get the path to the container log file.

$ docker inspect CONTAINER_ID --format "{{.LogPath}}" /var/lib/docker/containers/3d0305c254c33ff5e78d675f45e60fdcef65937ed8b53e21baf07f818d34ce9b/3d0305c254c33ff5e78d675f45e60fdcef65937ed8b53e21baf07f818d34ce9b-json.log
Code language: JavaScript (javascript)

If you have dockerd and containerd running on the same host as the docker container on Linux, you can cleaer the logs with a command like the following:

$ sudo truncate $(docker inspect CONTAINER_ID --format "{{.LogPath}}") --size 0 $ sudo bash -c ":> $(docker inspect CONTAINER_ID --format "{{.LogPath}}")"
Code language: JavaScript (javascript)

However, if you run docker inspect on Docker Desktop for Mac on macOS, you can get the path to the log file, but you cannot clear the log using the above way because /var/lib/docker is not present on macOS.
This is because running LinuxKit, a lightweight Linux, in a virtualized environment called HyperKit on macOS, and running containerd on it.

+------------+ | containerd | +------------+ | LinuxKit | +------------+ | HyperKit | +------------+ | macOS | +------------+

If you need to clear the container logs in the Docker Desktop for Mac, you need to clear the log files on LinuxKit, not macOS.

Connect to the LinuxKit

https://docs.docker.com/docker-for-mac/release-notes/#docker-desktop-community-2400 says to open the shell with the following command:

$ nc -U ~/Library/Containers/com.docker.docker/Data/debug-shell.sock
Code language: JavaScript (javascript)

Clear the container logs

Once you know how to connect, all you have to do is pipe the command to nc to clear the log.
However, since you cannot run the docker command on LinuxKit, you have to get the path to the log file by macOS.

$ echo ":> $(docker inspect CONTAINER_ID --format '{{.LogPath}}'); exit" | nc -U ~/Library/Containers/com.docker.docker/Data/debug-shell.sock
Code language: JavaScript (javascript)

Since it is hard to do this every time, it might be better to define a shell function.

clear_docker_logs() { echo ":> $(docker inspect ${1} --format '{{.LogPath}}'); exit" | nc -U ~/Library/Containers/com.docker.docker/Data/debug-shell.sock }
Code language: JavaScript (javascript)

By running the above shell function, you can clear the log of the container with the container ID passed as an argument.
Note that if you are installing netcat with brew, you cannot use nc -U and an error will occur. In that case, just run /usr/bin/nc with the absolute path.

Appendix

https://gist.github.com/BretFisher/5e1a0c7bcca4c735e716abf62afad389 says an example of serial connection with socat and screen, which may be easier to use when doing something on LinuxKit.

Leave a Reply