My Docker Cheat Sheet

Here are few commands that I find myself using a lot when I am working with Docker

Pull docker image from registry

gcloud docker -- pull gcr.io/my-project/my-image

Run pulled image locally

docker run -i -t gcr.io/my-project/my-image /bin/bash

SSH into running container

# use 'docker ps' to get container id
docker exec -it <CONTAINER ID> bash

Here is a hacky bash function that I wrote because I was tired of finding container ids and then typing out full command

# get bash shell on docker container.
# works only if one container is running
function get_bash_docker() {
  count=$(docker ps -q | wc -l)
  if [[ $count = 1 ]]; then
    container_id=$(docker ps -q)
    echo "Getting bash shell in ${container_id}"
    docker exec -it ${container_id} bash
  else
    # do not show running container if no containers are running
    if [[ $count = 0 ]]; then
      echo "No running containers"
      return 0
    fi
    # show running containers
    echo "Can't decide, $count containers are running"
    
    echo $(docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Image}}")
    
    echo "SSH into container using CONTAINER ID"
    echo "docker exec -it <CONTAINER ID> bash"
    return 1
  fi
}

# Docker aliases
alias dssh="get_bash_docker"

Remove all local docker images

docker rmi -f $(docker images -a -q)

docker images -a -q will give IMAGE ID of all local images and docker rmi -f will remove images with force.

To remove single image, list all images using docker images -a and remove it using docker rmi -f <IMAGE ID>

Docker System Cleanup

Remove unused data in docker, and get some disk space back

# show docker disk usage
docker system df
# just remove dangling stuff
docker system prune
# this will remove all images, and volumes
docker system prune --all --volumes

Continue Reading