docker commands | Actually delete everything | Delete all images | Search

This code removes all Docker containers, regardless of their running status, by first listing their IDs and then using those IDs to target the docker rm command.

Run example

npm run import -- "Delete all containers"

Delete all containers

docker rm $(docker ps -a -q)

What the code could have been:

#!/bin/bash
# Remove stopped and running containers
# Usage: remove_containers.sh

# Get a list of all container IDs
container_ids=$(docker ps -a -q)

# Check if any containers were found
if [ -n "$container_ids" ]; then
  # Remove the containers one by one to avoid errors
  for id in $container_ids; do
    docker rm -f "$id"
  done
else
  # If no containers were found, print a message
  echo "No running or stopped containers found."
fi

This code snippet removes all Docker containers, both running and stopped.

Here's a breakdown:

  1. docker ps -a -q:

  2. $(...):

  3. docker rm:

In essence, this command provides a concise way to clean up all Docker containers on your system.