Jens Piegsa
Jens Piegsa

Reputation: 7485

Docker: clean up all stopped containers except data-only containers

What is the Docker way to clean up all stopped Docker containers but retain data-only containers?

How to clean up the according images?

Upvotes: 4

Views: 1752

Answers (3)

Jens Piegsa
Jens Piegsa

Reputation: 7485

Following Mykolas proposal I introduced a naming convention requiring all data-only containers to be suffixed by -data.

To remove all stopped containers, except those named *-data:

docker ps -a -f status=exited | grep -v '\-data *$'| awk '{if(NR>1) print $1}' | xargs -r docker rm

To remove all unused images afterwards:

docker rmi $(docker images -qa -f dangling=true)

(the images used by the data-only containers are retained)

Upvotes: 4

user2915097
user2915097

Reputation: 32166

May be you can, in the docker run command of all your data-only container add a -e "type=data-only", and then filter based on this criteria, either with a grep or with a docker inspect example, I start a container with sudo docker run -it -e type=data-only ubuntu bash root@f7e9ea4efbd9:/# and then sudo docker inspect -f "{{ .Config.Env }}" f7e shows [type=data-only PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

Upvotes: 3

Mykola Gurov
Mykola Gurov

Reputation: 8695

In general there is no definitive way to distinguish data-only from other containers. If you wish them to survive your cleansing, you could probably design a certain name scheme and have more elaborate scripts that wouldn't remote containers with name, say, starting with data-.

Upvotes: 5

Related Questions