How to Delete Containers Permanently in Docker

How to Delete Containers Permanently in Docker

Usually, Docker doesn’t delete stopped containers but instead only untags them. This process happens to avoid accidental deletion of stopped containers.

This article will discuss properly deleting unused and untagged containers to reclaim resources in Docker.

Delete Containers Permanently in Docker

In Docker, we have the remove command that will forcefully delete a specific image. This command is the docker rmi -f <image_id> for images and docker rm <container_id> for containers.

However, on paper, the command will not delete the container image but will only soft delete it by untagging the object.

If we check our stopped images using the command docker image ls -a, we can verify that the above command will only untag our images instead of removing them.

Example Output:

Untagged: my_image:latest

The following sections will discuss multiple scripts and parameters to assist us in permanently removing docker containers.

Prune Containers in Docker

When working with Docker, we can quickly accumulate many unused objects consuming significant disk space and cluttering the output produced by Docker commands. Unfortunately, Docker does not remove untagged and unused objects such as containers, images, volumes, and networks unless it explicitly tells us to do so.

We can quickly reclaim resources with container pruning by deleting containers in stopped status. For example, we can use the command below.

Example Code:

docker system prune -a

The -a flag will remove all unused images. After running, it will prompt us with the following message.

We can bypass this message by adding the above command with the -f force flag.

WARNING! This command will remove the following:
        - all containers with the stopped status
        - all network paths not used by at least one (1) container
        - all images without at least one (1) container associated with them
        - all cache
Are you sure you want to continue? [y/N]

Additionally, the above commands will not delete unused volumes attached to previous unused Docker containers. However, we can append and use the --volumes parameter to include the removal of unused volumes.

Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - Docker Container

Related Article - Docker Image