docker commands | Restart the docker service | Delete all containers | Search

This code cleans up a Docker system by removing all unused images, containers, networks, volumes, and build caches.

Run example

npm run import -- "Actually delete everything"

Actually delete everything

docker system prune -a

What the code could have been:

bash
#!/bin/bash

# Function to clean up unused Docker resources
clean_docker() {
  # Option to remove all unused data, including networks and volumes
  local -i confirm_remove_all=true

  # Ask user to confirm before proceeding
  while true; do
    read -p "Are you sure you want to remove all unused Docker data? (y/n): " confirm
    if [[ $confirm =~ ^[Yy]$ ]]; then
      break
    elif [[ $confirm =~ ^[Nn]$ ]]; then
      echo "Docker cleanup cancelled."
      return
    else
      read -p "Invalid input. Please enter 'y' or 'n': " confirm
    fi
  done

  # Remove all unused data
  docker system prune -a --force
}

# Call the function
clean_docker

This code snippet uses the docker system prune command with the -a flag to remove all unused Docker images, containers, networks, volumes, and build caches.

Here's a breakdown:

  1. docker system prune:

  2. -a:

In essence, this command cleans up your Docker system by removing any resources that are no longer in use.