Useful Docker Bash functions and aliases
I type a lot of Docker commands every day. As a result I’ve made a habit
of creating Bash functions and aliases that I find useful and adding them to
my .bash_profile
.1
Getting the IP address
My first useful alias, dip
, is a short-cut to the docker inspect
command that allows you to inspect a container. One of the command’s
features is using the --format
flag to select a subset of the
inspection data. In this case I’m returning the container’s IP address.
This is my alias:
{% raw %}alias dip="docker inspect --format '{{ .NetworkSettings.IPAddress }}'"{% endraw %}
You can then type dip
and the container ID or name:
|
|
This will return the IP address of the specific container.
Removing containers
Once you’re done with a container it is easy to use the docker rm
command to remove it. But sometimes you want to delete a lot of
containers at once. This function provides a shortcut that removes all
non-running containers. It works by passing the output of the docker ps -q -a
command, which returns a list of container IDs, to the
docker rm
command.
To do this removal I wrote this function:
|
|
I can then run:
|
|
You can see that three containers have been removed but one running container has been skipped.
Removing images
Very similar to the function for removing containers is my function for
removing images. It passes the output from the docker images -q
command to the docker rmi
command.
This is the function.
|
|
And when run we’ll see:
|
|
We can see it has removed some images but skipped another that is in use.
Running a different types of containers
Next I have two simple aliases that provide shoutcuts to my most common options for running interactive and daemonized containers.
The first alias runs a daemonized container.
|
|
I use it like so:
|
|
This will launch a daemonized container running my jamtur01/ssh
image. I could also add a command override at the end of the command
also.
My second alias is very similar but runs an interactive container instead.
|
|
I use this like so:
|
|
This will launch a interactive container with a TTY running the
ubuntu
image and executed with the /bin/bash
command.
Docker build function
Finally I have a function for interacting with the docker build
command.
The function allows me to skip typing the -t
flag for tagging my
new images.2
|
|
I use it like so:
|
|
It assumes a Dockerfile
in my current directory and then builds that
file and tags the subsequent build with jamtur01/ssh
.
I hope those are useful to folks and feel free to add others you use in the comments.