Docker One-liners

When working with docker containers, we often face use cases where vanilla docker commands won't be sufficient. Below are such instances, where we "compose" multiple commands to get the results we want. Ample experience in bash cli environment and Linux utilities is assumed.

List Available Tags of an Image

echo -e nginx | xargs -I{} echo curl -L -s 'https://registry.hub.docker.com/v2/repositories/library/{}/tags?page_size=1024' | bash | jq '."results"[]["name"]'
  • Change nginx to the image name to be searched by.

  • Filter further using grep like grep alpine, grep 'alpine\|stable' etc.

  • Search for the official image

      docker search nginx | grep -i official
    

Check the User of Running Container

docker exec -t <container> whoami
echo -e "\nContainer (whoami)\n=================="; \
paste  <(docker ps | awk '{print $NF}' | grep -vi names) <(docker ps -q | xargs -I{} docker exec -t {} whoami) | column -t
  • awk { print $NF } prints the last column

  • paste command merges the lines one after the other

  • column -t formats output as table

  • xargs -I {}stores the argument to be passed to the command

echo -e "\nContainer (whoami)\n=================="; \
paste  <(docker ps | awk '{print $NF}' | grep -vi names) <(docker ps -q | xargs -I{} docker exec -t {} whoami) | column -t

Container (whoami)
==================
postgres     root
kafka1       appuser
zoo1         appuser
redis-cache  root
gitea        root
gitea-db     root
mongo        root

List the IP Address of Container(s)

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container>
paste <(docker ps | awk '{print $NF}' | sed 1,1d) <(docker ps -q | xargs docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}') | column -t
  • sed 1,Xd deletes the first 'X' lines in the stream

  • Replace IPAddress with MacAddress for mac address

Clear Container(s) log

docker inspect --format='{{.LogPath}}' <container> | xargs sudo truncate -s 0
docker ps -q | xargs docker inspect --format='{{.LogPath}}' | xargs sudo truncate -s 0

List Containers by Memory Usage

docker stats --no-stream --format "table {{.Name}}\t{{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" | sort -k 4 -h

List the Process ID of running Containers

for i in $(docker container ls --format "{{.ID}}"); do docker inspect -f '{{.State.Pid}} {{.Name}}' $i; done

List Images by Size

docker images --format "{{.ID}}\t{{.Size}}\t{{.Repository}}" | sort -k 2 -h

Force "clean build" of Images

docker build --no-cache
docker-compose build --no-cache &&
docker-compose up -d --force-recreate