简体   繁体   中英

Kill docker-compose containers without docker-compose.yml file

I have some docker containers provisioned by docker-compose with restart: always flag. But I accidentally delete docker-compose.yml file.

How do I delete those containers so that they will not restart automatically?

Without the compose file, docker-compose can't guess the name of the containers that need to be killed. You need to do that manually using docker command:

docker container ls
docker rm -f <container-name-or-id>

You can use docker ps -a to list all the running containers. After you can use docker stop container-name to stop individually the containers you want and after you can use docker rm $(docker ps -a -q) to delete and remove all the stopped containers.

Also if you want to delete the docker images as well you can use docker images to list the existing images and after docker rmi image-name to delete the image.

I had a similar issue - I didn't want to fetch the .yml files just to remove the containers. As docker-compose adds labels to the containers, we can use these to filter the matching containers and then remove them.

To remove all the containers that docker-compose created for project ProjectName (normally the name of the folder where the docker-compose.yml was) in shell (bash or similar), execute the following:

docker ps --filter 'label=com.docker.compose.project=ProjectName' --format {{.ID}} | xarg -n 1 docker rm --force --volumes

docker ps with the filter provides the list of containers, the format is provided so that only container IDs are printed
xargs -n 1 - takes the list of container IDs and executes the target command on each of them providing the container ID as the argument to the target
docker rm removes existing containers
--force - to also stop running containers (otherwise running containers would not be stopped or removed)
--volumes - to also remove any anonymous volumes associated with the containers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM