Category: Programming
Tags: #command-line #bash #docker #devops
Published: 2020-02-01

Command to Shell into a Docker Container

I decided to simplify the process of shelling into a container by creating a script that uses the image name to search for the container id then executes a bash shell. This won't work for everyone's work flow but, it saves me a buch of typing.

echo "Looking for $1"
OUT="$(docker ps | awk '{if( $2==container ) print $1}'-v container=$1)"

if [ ${#OUT} -eq 0 ]
    echo "Unable to locate a container running the image $1"
    exit 1

echo "Executing shell for Container ID:${OUT} running image $1"

docker exec -it ${OUT} bash



Create the file in /usr/local/bin, naming it d-s.

Make it executable:

chmod +x /usr/local/bin/d-s


d-s imagename


So, lets take a look at how this is working. My typical workflow requires

docker ps

Which would output something like:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                      NAMES

3a44bd8f52da        maxcpq              "docker-php-entrypoi…"   22 seconds ago      Up 21 seconds>80/tcp,>443/tcp   maxcpq_app_1

1e795b1b0cc0        mysql:5.7           "docker-entrypoint.s…"   23 seconds ago      Up 22 seconds>3306/tcp, 33060/tcp          maxcpq_mysql_1

I then copy the container ID and shell into the container by typing:

docker exec -it 3a44bd8f52da bash

With the exception of the parameter, the whole thing could be handled as an alias but, not being able to specify the container negates the whole purpose.

Everything is self explanatory with the exception of the line that assigns the container ID to the OUT variable.

This is accomplished by first taking the output of 'docker ps' and piping it through awk. The awk script looks like this:

awk '{if( $2==container ) print $1}'-v container=$1)

awk thinks in columns so the if statement is saying, if column2==container, print column1. Now, container is actually a variable which is assigned using the -v switch. The $1 being assigned to container variable is outside of the awk script and is actually the 1st command line parameter being passed to the script, not the calumn. The only script parameter is the container name so the container variable is assigned the command line parameter.

If the awk command is successful then the OUT variable will contain the container ID. It will then be passed to the docker exec command.