This process that runs on the host system can be anything from a web server, a database server, or any application that you containerized.
Therefore, when the container is stopped, sometimes, the processes associated with that container may not be properly cleaned. This can be due to several factors such as zombie containers. This leaves what is called an orphaned container. Although the orphaned containers do not necessarily cause any significant performance impact on the Docker engine, they can consume the resources such as the disk space.
In this tutorial, we will learn how to remove the orphaned containers in Docker using the docker-compose command.
Requirements:
To follow along with this tutorial, ensure that you have the following:
- A host system with the Docker Engine installed
- Permission to run the Docker commands on the host system
Docker “Compose Down” Command
We can access the “docker compose down” command in the Docker CLI tools to stop and remove the containers or networks. We can use this command to remove the orphaned containers.
The command syntax is as follows:
The command supports the following options:
- –remove-orphans – This removes the containers for the services that are not defined in the compose file. By default, it is set to false.
- –rmi – This allows the command to remove the images that are used by services.
- –timeout – This specifies the shutdown timeout in seconds.
- –volumes – This removes the named volumes that are declared in the “volumes” section of the Compose file.
Once you run the previous command, the Docker engine will stop and remove the containers, networks, volumes, or images that are created when running the “docker up” command.
By default, the command removes the containers for the services that are defined in the Compose file and those that are specified in the “networks” section.
To remove the orphaned containers, run the following command:
Remove the Orphaned Images
We can also remove the orphaned images using the “docker rmi” command. We can then use the -f option and pass it, setting the dangling property to true.
Finally, to remove the images, use the -q flag as shown in the following command:
This should find all the dangling images and remove them.
Conclusion
In this tutorial, you learned how to remove any orphaned containers, networks, volumes, and images in Docker. Regularly cleaning up the stopped and orphaned containers can keep the host system clean and prevent it from consuming unnecessary resources.