exit and delete all but the latest docker container

I currently have a lot of docker containers running that are no longer used.
So many actually that it would take a while to exit and quit them all manually.

I was wondering if there was a way to exit and delete all of them except for the latest one ?

  • Executing docker run command from config file
  • Docker ubuntu container can ping archive.ubuntu.com but not apt-get
  • Vaultier is unusable for docker/ubuntu/debian (Python)
  • Can I reference the service name docker-compose.yml
  • docker plugin not running parallel builds
  • Docker exec versus nsenter: Any gotchas?
  • Docker - Properly Mounting Host Directory in Docker Container (Windows)
  • Run Go app created in windows in Docker container (Ubuntu)
  • ERROR: Registering runner. forbidden (check registration token)
  • How to access postgres database on host from within docker container?
  • Docker Upgrade from v1.11 to v1.12 using apt-get on Ubuntu 14.04.4 LTS
  • How to stop the client IP address getting lost in a Cloudflare/Docker/NGINX/LAMP site?
  • One Solution collect form web for “exit and delete all but the latest docker container”

    A quick approach to do this is the following:

    First, stop all containers with this command:

    docker stop $(docker ps -aq)

    Then, start the container that you want to keep using:

    docker start container_name

    And finally, use docker container prune, which removes all stopped containers.

    docker container prune

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.