Reputation:
I have my containers scattered into multiple docker-compose.yml
files (https://docs.docker.com/compose/extends/). 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:
./myscript.sh 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:
./myscript.sh 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.
services:
db:
image: ...
container_name: shared-db
apache:
image: ...
container_name: shared-apache
From the above yml
, I'd have to get the names shared-db
and shared-apache
.
Upvotes: 1
Views: 2404
Reputation: 141165
Just use docker-compose kill
:
docker-compose -f shared/docker-compose.yml -f project1/docker-compose.yml -f project2/docker-compose.yml kill
The option -f
should come before the command to docker-compose
, that way it will be parsed as include files. You can use all possible docker-compose
commands that way.
Upvotes: 1
Reputation:
grep container_name: */docker-compose.yml | awk '{print $3}'
or:
grep container_name: */docker-compose.yml | sed 's/^.*: //'
Upvotes: 1
Reputation: 311711
As long as you are happy with myscript.sh kill
killing any container started with docker-compose
, you can use the labels that docker-compose
applies to containers to identify targets.
To find all containers started using docker-compose
:
docker ps --filter 'label=com.docker.compose.project'
So you could do something as simple as:
docker ps --filter 'label=com.docker.compose.project' -q |
xargs docker kill
See the docker ps
documenation on filtering for more information.
Upvotes: 2