Bash: get a list of container names from docker-compose.yml

I have my containers scattered into multiple docker-compose.yml files ( They are separated based on the project, but a few containers are common to all projects. I have a neat shell script which lets me easily start a few projects at a time:

./ up project1 project2

This executes:

docker-compose up -d -f shared/docker-compose.yml -f project1/docker-compose.yml -f project2/docker-compose.yml project1 project2

This starts the containers project1, project2 & a few that are defined in the shared compose file, e.g. shared-db, shared-apache.

I now want to add to my shell script the option to kill the containers:

./ kill

Should execute:

docker kill project1 project2 shared-db shared-apache

The problem is getting the list of my containers. My current approach is to use docker ps --format '{{.Names}}', which isn’t ideal as it can list also containers that are not a part of these projects.

I’ve also tried using docker-compose kill, which needs to be executed for each docker-compose.yml file separately. I looped through all the files and it worked for the first one, but threw an error for the second:

ERROR: Service 'project1' depends on service 'shared-db' which is undefined.

The error is thrown because project1/docker-compose.yml has dependencies from shared/docker-compose.yml and they are unmet because shared was already killed.

The only way that comes to mind is somehow go through all the docker-compose.yml files and get a list of all the container names that are defined there, but I didn’t find any proper way to parse yml files in bash.

    image: ...
    container_name: shared-db

    image: ...
    container_name: shared-apache

From the above yml, I’d have to get the names shared-db and shared-apache.

Source: StackOverflow