In this short tip I will show you how to get the name of a container created with
docker-compose, so you can manipulate it.

Table of contents

The problem

docker-compose generates container names going by the following convention: <CURRENT_DIR>_<CONTAINER_NAME>_<INSTANCE_NUMBER>.
I needed to get my hands on container names so I can individually kill and remove them without messing up with the whole infrastructure.

Let’s first dissect the structure:

So for a config file like the one below, placed in ~/Documents/projects/webapp, your container would be named webapp_nginx_1:

  image: nginx
    - "80:80"
    - "443:443"

The solution

No matter how hard my problem was, I turned to my StackOverflow skills and quickly found that there was a way to parse only the basename from the whole pwd string, without complicated splits and parsing.
The thing I was looking for was Shell Parameter Expansion, which got me this thing: CONTAINER_NAME=${PWD##*/}_nginx_1.
What this allowed me to do was to get the current directory name, without the full path and concatenate that with what I wanted. Now I could docker rm my container peacefully.

There’s another problem, though, the fact that directory names like this: webapp-authentication-project, get turned into webappauthenticationproject.
For this, I resorted to sed so I could take out the underscores and dashes from the filename.

The final version of my code looks just like the snippet below:

CONTAINER_NAME=$(echo ${PWD##*/}_nginx_1 | sed s'/[ -]/_/g')

Now I can manipulate containers from any bash script, as long as I can get my hands on the $PWD and as long as I know the names they get in the YAML config file.

Image credits: Glen