When you run a project with Docker, sometimes you've just got to trash your container and start over. Well, it turns out that when you delete a project and all of its containers from Docker Desktop, there are resources that linger and end up getting reused when you rebuild your container, often causing issues that you'd hoped to resolve by deleting and rebuilding your container.
For a while I was using this command to purge the restorable cache after deleting a container:
But I recently found out that wasn't good enough, as a deeper investigation revealed resources from containers I had deleted three years before. With ChatGPT's help, I came up with this script to thoroughly scorched-Eath a Docker project. Save this script to a file named docker_squash.ps1
then run it in PowerShell, and you will be prompted to enter the name of the Docker project you wish to purge.
param ( [Parameter(Mandatory = $true)] [string]$keyword )
Write-Host "Search for Docker resources matching keyword: '$keyword'"
# --- Containers --- docker ps -a --format "{{.ID}} {{.Names}}" | ForEach-Object { if($_ -match $keyword) { $id = ($_ -split " ")[0] Write-Host "Stopping container: $id" docker stop $id | Out-Null Write-Host "Removing container: $id" docker rm $id | Out-Null } }
# --- Images --- docker images --format "{{.ID}} {{.Repository}}:{{.Tag}}" | ForEach-Object { if($_ -match $keyword) { $id = ($_ -split " ")[0] Write-Host "Removing image: $id" docker rmi -f $id | Out-Null } }
# --- Volumes --- docker volume ls --format "{{.Name}}" | ForEach-Object { if($_ -match $keyword) { Write-Host "Removing volume: $_" docker volume rm $_ | Out-Null } }
# --- Networks --- docker network ls --format "{{.ID}} {{.Name}}" | ForEach-Object { if($_ -match $keyword -and $_ -notmatch 'bridge|host|none') { $id = ($_ -split " ")[0] Write-Host "Removing network: $id" docker network rm $id | Out-Null } }
Write-Host "" Write-Host "Done squashing '$keyword' cockroaches with a hammer. You might have to restart Docker to totally flush the memory."
Keep in mind that this script can only do its job if the Docker engine is running, otherwise you'll get some error messages that look something like error during connect: Get "http:////./pipe/dockerDesktopLinuxEngine/v1.49/containers/json?all=1": open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified
.