Handy Bash functions for Docker

How to create shortcut commands via bash for Docker?

If you are working on docker regular bases and wonder how to write some shortcut commands for your daily use you will find this tutorial very useful. In order to create shortcut bash function first of all let's create a new file called bash_aliases.

Run following command to create this new file:

sudo nano ~/.bash_aliases

Now once it opens nano editor you can add following shortcuts and save the file:


# syntax: dr-cmd <container> <command>
dr-cmd() {
    docker exec -it $1 "${@:2}"

# syntax: dr-run <image>
dr-run() {
    docker run -it $1 /bin/sh

# syntax: dr-sh <container>
dr-sh() {
   docker exec -it $1 sh

# syntax: dr-log <container>
dr-log() {
  docker logs -f $1

# syntax: dr-build
dr-build() {
    docker build . -t $1
    docker run -p 8080:$2 $1

# syntax: dr-reset
dr-reset() {
    containerId=$(docker ps -a | grep $1 | cut -d" " -f1)
    imageId=$(docker inspect --format='{{.Image}}' $containerId)
    docker rm $containerId -f  && docker rmi $imageId

# syntax: dr-run-dead
dr-run-dead() {
  docker commit $1 $1-image > /dev/null
  docker run -it $1-image$*

# syntax: dr-reset-log
dr-reset-log() {
    truncate -s 0 $(docker inspect --format='{{.LogPath}}' $1)

# syntax: dr-ps
alias dr-ps='docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}\t{{.Ports}}"'

# syntax: dr-clean
alias dr-clean='docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q) && docker rmi $(docker images -a -q)'

Once you save above changes by Ctrl + x + yes shortcut you are now able to run this shortcut. Let's activate our newly created file so that we can run commands as we described in the file.

# activate our bash changes
source ~/.bash_aliases

Now, we are all set and can run our shortcut commands as below:

# show all docker containers running

# run specific command inside docker container
# without login into a container
# syntax: cr-cmd <container> <command>
dr-cmd my-container ls -la

# run a docker image
dr-run <image>

# log in to specific docker container
dr-sh <container>

# show container logs for docker container
dr-log <container>

# build and run container on port 8080
dr-build <image:tag> <inside-port>

# reset docker container and its image

# to run container that exited
dr-run-dead <image-name>

# reset/truncate docker container logs

# remove all unused images

Hope you have enjoyed this shortcut commands for docker. If you want to learn more about linux bash files try following article.

Bash Aliases