Shortcuts for Docker Learner

As a newbie of docker, I created some bash functions with auto-completion to help exploring docker. With tips in the previous post, you may use them in both local and remote environment.

The Code

Paste file below in e.g. ~/.bash_aliases_shared.

Updated on 4 Jun, so shortcuts below may be different comparing to the gif above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# install docker
alias install-docker="wget -qO- https://get.docker.com/ | sh"

# list all running containers
function dls {
  a=$(sudo docker ps -aq | xargs sudo docker inspect --format="  ")
  echo "$a" | sed -e 's/.\{58\} \//  /' -e 's/ false/(down)/' -e 's/ true/(up)/'
}

# list all running containers (name only)
function dlsn {
  dls | awk '{print $2}' | sed -e 's/(.*//'
}

# view logs of a docker container
function dlog { sudo docker logs $1 $2; }

# go into a container (linux kernel > 3.18)
function dbind { tmux rename-window $1; sudo docker exec -i -t $1 bash; }

# remove a container
function drm { sudo docker kill $1; sudo docker rm $1; }

# create a detached container
# usage: dn [image] [name]
# default: dn ubuntu <random>
function dn {
  image=${1-ubuntu}
  if [[ "$2" != "" ]]; then
    name_opts="--name=$2"
  fi
  id=$(sudo docker run -d -v `pwd`:/host $name_opts $image tail -f /dev/stdout)
  dbind $id
}

# list image
alias di="sudo docker images"

# turn container into image
# usage: dci container1 image1
function dci { msg=${1-nomsg}; docker commit -m "$msg" $1 $2; }

# create a new persistant ubuntu 14 container and bind in it
# usage: dnewu14 ubuntu2
function dnu { dn ubuntu $1; }

# usage: dcp a.txt container1
function dcp { tar -cf - $1 | docker exec -i $2 /bin/tar -C / -xf -; }

# auto completion for dlog/dbind/drm
if type complete > /dev/null; then
  _docker_containers() {
    COMPREPLY=( $( compgen -W "$( dlsn )" -- ${COMP_WORDS[COMP_CWORD]} ) ); return 0
  }
  complete -F _docker_containers dlog
  complete -F _docker_containers dbind
  complete -F _docker_containers drm
fi

Comments