Cleanup docker images and containers
Docker is a fantastic tool to create lightweight containers for any application or stack, powered by LXC, which im a big fan of. There are no special ways of building docker images, some folks are using Chef/Puppet, etc. However, docker brings a very simple way to define image build steps: Dockerfiles.
Example of the Dockerfile:
FROM ubuntu:12.04
MAINTAINER Dan Sosedoff "dan.sosedoff@gmail.com"
# Update system
RUN apt-get update -y
RUN apt-get upgrade -y
# Setup SSH server
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
# Start SSH server
CMD /usr/sbin/sshd -D
Basically, each RUN
command will create an intermediate container. If you're in the
process of developing your images, running lots of build commands will at some point
make your system run out of disk space. There are few ways to reduce this overhead.
Cleanup after build
Typically i build images with the following command:
docker build -t=myimage -rm=true .
This will build a new image with name myimage
and after build is complete
Docker will automatically remove intermediate containers
Flush everything
Sometimes its necessary to get rid of all containers and images to start from scratch. You can do everything by hand, but it might take a while. Instead, here are 2 scripts to handle that for you.
Container cleanup script:
#!/bin/bash
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
And image cleanup script:
#!/bin/bash
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
docker rmi $(docker images -a -q)
Running both scripts will get rid of all containers (stopped or running) and remove all existing images so you can start from scratch.
NOTE: If you delete image before you delete any container that uses it you'll have an issue with orphaned NFS nodes and only machine reboot will fix it. Hopefully this issue will be resolved soon.