Using Docker Commands with Aliases and Bash Functions
We use Docker at work and so I find myself running the same commands over and over. To save time I saved frequent docker and docker-compose commands as aliases and functions.
Aliases
These aliases save a few key strokes for running often used commands:
1# general compose aliases
2alias dcb="docker-compose build"
3alias dcu="docker-compose up"
4alias dcub="docker-compose up --build"
5alias dcs="docker-compose stop"
6
7# list all running containers
8alias dps="docker ps"
9
10# stop all running containers
11alias dsa="docker ps -q | awk '{print $1}' | xargs -o docker stop"
12
13# list dangling images
14alias dlist="docker volume ls -qf dangling=true"Functions
Some commands are better saved as functions.
When developing and writing unit tests, I will often want to get to the bash prompt in the test container. I saved this function as dcbash.sh and aliased it as dcbash to save a few keystrokes:
1#!/bin/bash
2
3# Run a bash shell in the specified container (with docker-compose)
4
5# a simple help menu: if no arg is passed in, the function usage is printed
6if [ $# -ne 1 ]; then
7 echo "Usage: $FUNCNAME CONTAINER_NAME"
8 return 1
9fi
10
11# this echo is optional but I like to maintain familiarity with the actual command
12echo "CMD: docker-compose run --entrypoint="" $1 /bin/bash";
13docker-compose run --entrypoint="" $1 /bin/bashFor example dcbash pretend-service-test runs docker-compose run --entrypoint="" pretend-service-test /bin/bash.
Images take up space and are not auto removed. I’ve encountered errors before about lack of space so a periodic tidy up of unused images and containers is recommended.
I saved this as drmi.sh and it removes dangling Docker images:
1#!/bin/bash
2
3# remove docker dangling images
4docker rmi $(docker images --filter "dangling=true" -q --no-trunc)I saved this as drmc.sh and it removes all non-running containers:
1#!/bin/bash
2
3# removes all non-running containers
4docker rm $(docker ps -q -a);These aliases and functions help my productivity by saving a key strokes and saving time looking up the commands for a periodic tidy up of Docker images and containers. I hope they may prove useful to you too.