docker rm
For example uses of this command, refer to the examples section below.
Options
| Name, shorthand | Default | Description |
| —force , -f | Force the removal of a running container (uses SIGKILL) | |
| —link , -l | Remove the specified link | |
| —volumes , -v | Remove anonymous volumes associated with the container |
Examples
Remove a container
This removes the container referenced under the link /redis .
Remove a link specified with —link on the default bridge network (—link)
This removes the underlying link between /webapp and the /redis containers on the default bridge network, removing all network communication between the two containers. This does not apply when —link is used with user-specified networks.
Force-remove a running container (—force)
This command force-removes a running container.
The main process inside the container referenced under the link redis will receive SIGKILL , then the container will be removed.
Remove all stopped containers
Use the docker container prune command to remove all stopped containers, or refer to the docker system prune command to remove unused containers in addition to other Docker resources, such as (unused) images and networks.
Alternatively, you can use the docker ps with the -q / —quiet option to generate a list of container IDs to remove, and use that list as argument for the docker rm command.
Combining commands can be more flexible, but is less portable as it depends on features provided by the shell, and the exact syntax may differ depending on what shell is used. To use this approach on Windows, consider using PowerShell or Bash.
The example below uses docker ps -q to print the IDs of all containers that have exited ( —filter status=exited ), and removes those containers with the docker rm command:
Or, using the xargs Linux utility;
Remove a container and its volumes (-v, —volumes)
This command removes the container and any volumes associated with it. Note that if a volume was specified with a name, it will not be removed.
Remove a container and selectively remove volumes
In this example, the volume for /foo remains intact, but the volume for /bar is removed. The same behavior holds for volumes inherited with —volumes-from .
How to Remove All Docker Images, Containers, Volumes, Networks and Unused Resources
Docker is taking the world by storm because it is a valuable open-source platform that allows applications to run without using an actual virtual machine of any kind. This gives users the flexibility to run and test applications in software containers without the need to worry about compatibility, turning your virtual private server into a great development platform.

In this tutorial, we’ll teach you the basic commands every user should know, such as how to remove unused Docker images, containers, volumes, and networks.
Removing All Unused Docker Resources
Important! Remember, first you need to access your VPS using SSH and have Docker installed on your machine.
Docker doesn’t remove any unused data by itself, which can result in cluttering your disk space.
If you’d like to remove all images, containers, and networks that are not associated with a container
This command will remove everything, including dangling images and stopped containers, as the following message will tell you:
Pro Tip
Notice that this will remove dangling Docker images only.
In order to include all unused images, execute the following command:
Here’s the warning message that you’ll see before continuing:
However, the previous two commands will not touch unused volumes – this is done deliberately for safety reasons.
If you’d like to remove that as well, use the following command:
Important! Take note that using both rm and prune commands is not reversible.
How to Remove Docker Images?
In order to view all of your Docker images, you can use:
If you want to remove Docker image or a few, you can use this command and list the IMAGE ID as shown here:
To remove dangling images that are most recent and untagged, we will use the “docker remove all images” command as shown here:
However, to remove Docker images that are present in existent containers that are also tagged, we can use this:
If you wish to remove all images, for example, that may fall under a specific time frame, use the command:
If you want to know more about –filter flags, check out the official documentation page.
Pro Tip
In order to force executing any “remove” command at any given time, use the -f or –force flag.
How to Remove Docker Containers?
Similarly to before, in order to see the list of all Docker containers, you will need to run this command:
If you want to remove a specific container, enter the CONTAINER ID as shown in this example:
To remove all the containers that stopped in the application, follow this command:
Take note that this will remove all stopped containers. In order to view the list of what containers will be deleted using the beforementioned command, use the –filter flag:
To limit the removal of containers that stopped, for example, according to the time frame, you can use the following command:
If you want to remove a container once you’re done working with it, you start one by adding a –rm flag. Here’s an example of how to remove such container:
When you’re done, the container will be deleted automatically.
How to Remove Docker Volumes?
Volumes are used for multiple containers, and it is very likely there will be a number of either unused or stopped volume files.
These files are not removed automatically, neither is there a setting in Docker to do so, as that can cause significant loss or damage to data.
First, to get all Docker volume IDs, use the following command:
If you want to remove a certain volume, use this command followed by the VOLUME NAME:
To remove all unused volumes using a single command, you can use the following:
If Docker volumes have labels attached to them, you can also use this:
In this example, the command will only remove those volume files which are not labeled and assigned with the “keep” label.
How to Remove Docker Networks?
Though Docker networks don’t take much disk space, it can cause some problems if unnecessary files are not cleared from the disk.
One problem is that it creates rules for iptables and bridge networks with routing table entries, which can cause some issues in the long run.
For a full list of NETWORK IDs, use the following command:
In order to remove a specific network, you can use:
If you wish to remove all unused networks, use the following command:
For a filter based on the time frame, 24 hours in this example, you can simply enter instead:
Pro Tip
If you get an error when trying to remove a certain network, it means that an existing container uses that specific network and will have to be removed before continuing.
Why Use Docker?
Working with Docker allows the app to run more smoothly, no matter the system, screen size, or web browser it is being used on. Docker makes it easy to deploy, launch, and then test applications without much difficulty. In short, it is quick, saves time, and is easy to learn.
Here are some more examples of why Docker is such a popular container platform.
- Cost-effective and cost-efficient. Unlike more traditional container platforms, Docker’s infrastructure is minimal, which helps to save the organization a lot of money on virtual machines and related equipment. Most importantly, Docker can be handled with fewer employees, which also helps save money if your budget’s too tight.
- Great overall compatibility. Docker allows the developers to create, run, and test applications on the container, ensuring a smooth operation on any system. It provides plenty of room for experimentation that enables software developers to make applications with fewer bugs. It also allows it to be more portable with easy to set up code bases.
- Faster productivity. One of Docker’s more prominent features is that it allows for a single command to take care of further steps. This adds more efficiency to your workflow and faster configuration of an application, increasing productivity.
- Multi-cloud platform compatibility. Docker allows multi-cloud computing, a method many systems all over the world have fully embraced it. Amazon Web Services (AWS) and the Google Compute Platform (GCP) are just some of the examples where Docker is highly favored. Many applications that, include OpenStack, Microsoft Azure, Chef, Puppet, and more, are highly compatible with Docker containers.
- Increased security. Docker is secure and fast, which means that each application running on Docker containers stays isolated from each other, causing fewer security issues in return. It allows the developer to take charge of the full management of the application and the traffic flow without causing server or security issues.
Conclusion
Nowadays, Docker is gaining considerable momentum and is used by many famous companies worldwide. It is one of the best platforms to date that allows more convenient development solutions, allows unlimited testing and experimentation to create applications quickly and efficiently.
In this tutorial, you’ve learned how to clear unused Docker images, containers, volumes, and networks. If you have any more questions, feel free to leave a comment down below.
Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.
Удаление образов, контейнеров и томов Docker

Docker позволяет легко помещать приложения и службы в контейнеры, чтобы их можно было запускать где угодно. Однако при работе с Docker можно легко накопить чрезмерное количество неиспользуемых образов, контейнеров и томов данных, замедляющих работу и потребляющих место на диске.
Docker предоставляет все необходимые инструменты для очистки системы из командной строки. В этом руководстве с полезными советами кратко описываются полезные команды для освобождения места на диске и организации системы посредством удаления неиспользуемых образов, контейнеров и томов Docker.
Использование этого руководства:
- Это руководство в формате полезных советов содержит автономные сниппеты для командной строки
- Вы можете перейти к любому разделу, актуальному для задачи, которую вы пытаетесь выполнить.
Синтаксис замены команды command $( command ) , используемый в командах, доступен во многих популярных оболочках, включая bash, zsh и Windows Powershell.
Очистка всех неиспользуемых или не связанных с контейнерами образов, контейнеров, томов и сетей
В Docker имеется команда, очищающая все не связанные с контейнерами ресурсы, в том числе образы, контейнеры, тома и сети:
Чтобы удалить все остановленные контейнеры и неиспользуемые образы (а не только образы, не связанные с контейнерами), добавьте в эту команду флаг -a :
Удаление образов Docker
Удаление одного или нескольких конкретных образов
Используйте команду docker images с флагом -a , чтобы найти идентификатор удаляемых образов. Эта команда покажет вам все образы, включая промежуточные слои образов. Когда вы определитесь с составом удаляемых образов, вы можете передать их идентификаторы или теги в docker rmi :
Список:
Удаление:
Удаление образов, не привязанных к контейнеру
Образы Docker состоят из нескольких слоев. Несвязанные образы — это слои, не имеющие связей с каким-либо образами с тегами. У них нет никакого назначения, и они просто занимают место на диске. Их можно найти, добавив флаг фильтра -f со значением dangling=true в команду docker images . Если вы уверены, что хотите удалить их, вы можете использовать команду docker images purge :
Примечание. Если вы создали образ и не пометили его тегами, он будет отображаться в списке несвязанных образов, поскольку он не привязан к образу с тегом. Этого можно избежать, указав тег при сборке образа. Также вы можете помечать тегами уже существующие образы с помощью комнады docker tag.
Список:
Удаление:
Удаление образов по шаблону
Вы можете найти все образы, соответствующие определенному шаблону, используя комбинацию команд docker images и grep . Когда вы будете довольны, вы можете удалить их, используя awk для передачи идентификаторов в docker rmi . Эти утилиты не предоставляются Docker и могут быть доступны не во всех системах:
Список:
Удаление:
Удаление всех образов
Для вывода всех образов Docker в системе нужно добавить флаг -a в команду docker images . Если вы уверены, что хотите удалить их все, добавьте флаг -q для передачи идентификатора образа в docker rmi :
Список:
Удаление:
Удаление контейнеров
Удаление одного или нескольких конкретных контейнеров
Используйте команду docker ps с флагом -a для поиска имен или идентификаторов контейнеров, которые вы хотите удалить:
Список:
Удаление:
Удаление контейнера при выходе
Если вы создаете контейнер, который вам не будет нужен после завершения его использования, вы можете использовать команду docker run —rm для его автоматического удаления при выходе.
Запуск и удаление:
Удаление всех контейнеров, из которых выполнен выход
Вы можете найти контейнеры с помощью команды docker ps -a и отфильтровать их по статусу: created (создан), restarting (перезапускается), running (работает), paused (пауза) или exited (выполнен выход). Чтобы просмотреть список контейнеров, из которых выполнен выход, используйте флаг -f для фильтрации по статусу. Убедитесь, что вы хотите удалить эти контейнеры, и используйте флаг -q для передачи идентификаторов в команду docker rm .
Список:
Удаление:
Удаление контейнеров с использованием нескольких фильтров
Фильтры Docker можно комбинировать, повторяя флаг фильтра с дополнительным значением. В результате выводится список контейнеров, соответствующих любому из указанных условий. Например, если вы хотите удалить все контейнеры со статусом Created (статус, который может возникнуть при запуске контейнера недопустимой командой) или Exited, вы можете использовать два фильтра:
Список:
Удаление:
Удаление контейнеров по шаблону
Чтобы найти все контейнеры, соответствующие определенному шаблону, используйте сочетание команд docker ps и grep. Когда вы будете удовлетворены списком удаляемых контейнеров, используйте awk и xargs для передачи идентификаторов в команду docker rmi . Обратите внимание, что эти утилиты не поставляются Docker и могут быть доступны не во всех системах:
Список:
Удаление:
Остановка и удаление всех контейнеров
Для просмотра контейнеров в системе используется команда docker ps . При добавлении флага -a будет выведен список всех контейнеров. Если вы уверены, что хотите удалить их, добавьте флаг -q для передачи их идентификаторов командам docker stop и docker rm :
Список:
Удаление:
Удаление томов
Удаление одного или нескольких томов — Docker 1.9 и выше
Используйте команду docker volume ls для определения названий томов, которые вы хотите удалить. Затем вы можете удалить один или несколько томов с помощью команды docker volume rm :
Список:
Удаление:
Удаление несвязанных томов — Docker 1.9 и выше
Поскольку тома существуют независимо от контейнеров, при удалении контейнера тома не удаляются автоматически. Если том существует, но не связан ни с какими контейнерами, он называется несвязанным томом. Чтобы найти такие тома и убедиться в необходимости их удаления, вы можете использовать команду docker volume ls с фильтром, чтобы в результатах выводились только несвязанные тома. Если список вас устроит, вы можете удалить все тома с помощью команды docker volume prune :
Список:
Удаление:
Удаление контейнера и его тома
Если вы создали том без имени, его можно удалить одовременно с контейнером, используя флаг -v . Обратите внимание, что это работает только с томами без имени. При успешном удалении контейнера отображается его идентификатор. Обратите внимание на отсутствие указания на удаление тома. Если у тома нет имени, он удаляется из системы незаметно. Если у тома есть имя, он сохраняется в системе без уведомлений.
Удаление:
Заключение
В этом руководстве рассказывается о некоторых распространенных командах, используемых для удаления образов, контейнеров и томов с помощью Docker. Существует много других комбинаций команд и флагов. Более полную информацию можно найти в документации Docker по командам docker system prune , docker rmi , docker rm и docker volume rm . Если вы хотели бы увидеть в этом руководстве часто встречающиеся задачи по очистке системы, задавайте вопросы и оставляйте свои предложения в комментариях.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Name already in use
docker-ce / components / cli / docs / reference / commandline / rm.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Remove a container
This removes the container referenced under the link /redis .
Remove a link specified with —link on the default bridge network
This removes the underlying link between /webapp and the /redis containers on the default bridge network, removing all network communication between the two containers. This does not apply when —link is used with user-specified networks.
Force-remove a running container
This command force-removes a running container.
The main process inside the container referenced under the link redis will receive SIGKILL , then the container will be removed.
Remove all stopped containers
Use the docker container prune command to remove all stopped containers, or refer to the docker system prune command to remove unused containers in addition to other Docker resources, such as (unused) images and networks.
Alternatively, you can use the docker ps with the -q / —quiet option to generate a list of container IDs to remove, and use that list as argument for the docker rm command.
Combining commands can be more flexible, but is less portable as it depends on features provided by the shell, and the exact syntax may differ depending on what shell is used. To use this approach on Windows, consider using PowerShell or Bash.
The example below uses docker ps -q to print the IDs of all containers that have exited ( —filter status=exited ), and removes those containers with the docker rm command:
Or, using the xargs Linux utility;
Remove a container and its volumes
This command removes the container and any volumes associated with it. Note that if a volume was specified with a name, it will not be removed.
Remove a container and selectively remove volumes
In this example, the volume for /foo remains intact, but the volume for /bar is removed. The same behavior holds for volumes inherited with —volumes-from .