ctsh: a tool for running commands on Docker containers

Image for post
Image for post

So I’m doing a fair amount of testing of container configurations. To do this, I tweak the Dockerfile, build the image, and then run some commands in the container to test my configuration. One thing that has always been a little annoying is having to find the name of the container if I didn’t explictly give it an alias. I could certainly do that, but what if I just randomly spin up a container?

I decided to write a little command called ctsh that would basically let me run a command on a container by specifying a search query and an optional command to run (defaults to bash). The script then looks up the container id by matching the search query against the container id (so you can specify just part of the container id), the image name, or the name that docker assigned to it. Most of the time, you are running just one container with a particular image, so it should match right away. The script will then echo the docker command that it actually runs:

In some cases, however, you might have more than one container running with the same image. In this case, the script will prompt you for which container you want:

You can specify additional arguments that are a command to run. The additional arguments are appended to the docker exec command:

If you want to run a command involving a variable (a variable defined inside the container), you will need to use a special syntax:

Essentially, you are executing the sh command with a -c argument that is the command to run inside the sh command. The argument following that is double quoted and then single quoted inside that so that the stuff inside the single quotes is passed as a single argument to docker exec. You also have to escape the dollar sign so that the variable isn’t interpreted in the local host.

You can find the script here:

https://github.com/openshiftninja/dockertools/blob/master/scripts/ctsh

If you find this command helpful, or you have ideas for improving this script, please leave a comment below!

Originally published on April 24, 2018.

Written by

I'm a technology enthusiast, always searching for better ways of doing things. Lately that has been all things React. I also write a lot on Medium. :)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store