Custom command to interact with Docker containers

Main Thread 2 min read

I recently switched to using Docker for my local development environment on macOS. I've been pretty happy with it. But a tiny paper cut has been jumping into one of the containers.

Since each time I start my local environment the container IDs change, I'm always having to run docker container ps, copy the container ID, then pass it to docker exec.

While I'm sure there might be a better way, I wrote a simple command to help do all this with a single command.

I call it dec as an acronym for Docker Execute Container. I pass it a string reference of the Docker container I want to run. This string could reference any of the output from docker container ps. I normally reference the image name.

In my case, I have a few images which run to create my local stack. One for the LAMP container running the Apache web server and PHP. One for the MySQL server. And one for running PHPMyAdmin.

With this custom dec command, I can jump into the LAMP container by running:

1dec lamp

Or the container running MySQL by running:

1dec mysql

So much nicer than running the container ps command and then exec -it command.

As a bonus, I added a little check to see if the local working directory is a subdirectory of my workspace volume mount. If so, I automatically set the working directory of the container to match. You are welcome to remove or adjust this line of your own setup.

The dec command is included in my dotfiles. These also contain by custom Docker prompt. So you may already have copied my dotfiles.

If so, be sure to update your copy. Otherwise, you may add the following code to your ~/.bash_profile:

1function dec() {
2 containers=`docker ps | awk '{print $1,$2,$NF}' | grep -m 1 -F $1`
3 container_id=`echo $containers | awk '{print $1}'`
5 if [ -n "$container_id" ]; then
6 if [[ $PWD/ = /Users/*/workspace/* ]]; then
7 docker exec -w /var/www/"${PWD#*/workspace/}" -it $container_id /bin/bash
8 else
9 docker exec -it $container_id /bin/bash
10 fi
11 else
12 echo "No container found for query: '$1'"
13 fi

Find this interesting? Let's continue the conversation on Twitter.