DEV Community

Cover image for A Simple Docker Cleanup Script to Save Your Day
Itay Eylath
Itay Eylath

Posted on

A Simple Docker Cleanup Script to Save Your Day

Are you tired of dealing with cluttered Docker containers? 🐳
Or any issues as a Linux user? 🛠️
Or maybe, you are just a lazy FullStack developer? 🥱

If you find your development environment getting messy with containers that you no longer need, I have a nifty little script that will solve your Docker woes in no time :-)

The Magic Script: 🪄

Let me introduce you to docker-cleanup.sh - a simple yet powerful script that will give your Docker environment a fresh start

Here's what the script looks like:

# Check if there are any containers
if docker ps -a &> /dev/null; then
    echo "Removing existing containers..."
    # Remove all containers
    docker rm -f $(docker ps -a -q)
    # Restart Docker
    echo "Restarting Docker..."
    sudo systemctl restart docker
    # Print Docker status
    echo "Docker status:"
    sudo systemctl status docker | grep "Active:"
else
    echo "No containers to remove."
fi
Enter fullscreen mode Exit fullscreen mode

How It Works 🔍

  • Checks for Containers: The script starts by checking if there are any existing Docker containers.
  • Removes Containers: If containers are found, it removes all of them.
  • Restarts Docker: After cleaning up, the script restarts Docker to ensure everything is running smoothly.
  • Displays Status: Finally, it shows the status of Docker to confirm that everything is active and working.

How to Use It 💡

Using this script is super easy. Just follow these simple steps:

  1. Save the script as docker-cleanup.sh (recommend to save it on home dir)
  2. Open your terminal.
  3. Execute the script bash docker-cleanup.sh

A Personal Touch 🤗

I face Docker environment issues regularly. This script has become my go-to solution, and I find myself using it at least once a day before I start working. It's simple, effective, and saves me a ton of time and hassle. I hope it works just as well for you! 🤞

GitHub Repo

Happy coding!

Image description

Top comments (2)

Collapse
 
ameliacharellot profile image
amelia charlotte

"Great script! It's refreshing to find such clear and effective solutions. Your Docker cleanup guide was incredibly helpful and saved me a lot of time. Looking forward to more practical tips like this!"

Hire App Developers in India

Collapse
 
hectorlaris profile image
Héctor Serrano

Thank you for sharing!