How to delete all containers docker
How to delete all containers docker
Docker: How to Stop and Remove All Containers at Once
January 24
Stay connected
It’s an understatement to say that Docker is a game-changer for systems engineers and developers. You can run almost any application with a single command and customize it for your environment via a consistent container-based interface. But as containers proliferate, controlling them gets more complicated, too. Managing containers from the command line can be painful, but setting up an orchestration tool like Kubernetes or Docker Swarm is overkill for smaller systems.
Stopping and removing a container from the command line takes two steps. Stopping and removing two containers is four. And stopping and removing 10 containers is—well, you get the idea. Let’s look at how to make the Docker command line easier to use. We’ll focus on stopping and removing containers. Then, we’ll look at Docker Compose, another tool that makes managing smaller collections of containers easier.
These examples will be for systems that use Docker’s shell-based tools, including macOS, Linux, and Windows with WSL. You’ll need to have Docker installed, as well as docker-compose.
Stopping and Removing All Containers
For the Impatient
Here’s a command that will stop and remove all of the containers on your system, assuming the user running it is root or a member of the docker group.
How does this command work? Let’s take a closer look.
Listing Containers
The first part of the command lists all of the containers on the system. Here’s a screenshot of a system with four containers:
The -aq option tells docker ps to list all containers (-a) by container ID (-q). You can combine the two arguments after a single dash (—).
If you drop the a, you only see three containers:
That’s because one of them isn’t currently running. Here’s a long listing:
Here’s the other half of the display. You’ll want to refer to it later.
What’s Xargs?
The next two parts of the command to stop and remove all containers start with xargs. Xargs is a Linux utility that accepts entries from its input and executes the command you specify for each entry.
When you pass it to xargs without any additional arguments, it defaults to /bin/echo for its command, and it appends its input to the end of the command you specify:
This command transformed the output of docker ps to:
echo 344bf90e09e7
echo 8667dc69816a
echo 322f55c7b223
echo c5df9ef22d09
Since you didn’t tell echo to add a carriage return, it printed all four IDs on one line.
That’s not a very useful example. So, let’s get fancy.
Docker port lists information about network ports in a container.
You need to pass it the container ID and the port you’re interested in. So, we need to tell xargs how to run this command.
Here’s how to examine port 80 on all four containers.
Then it pipes (|) the output to xargs with -I ‘ID’ as the first two arguments. This tells xargs that when it sees ‘ID’ in the command that follows, replace it with the input from the pipe.
So, xargs transforms command docker port ‘ID’ 80 into these four commands:
docker port 344bf90e09e7 80
docker port 8667dc69816a 80
docker port 322f55c7b223 80
docker port c5df9ef22d09 80
The output from these four commands shows us that Docker has mapped three of the containers to ports 8083, 8082, and 8081. The fourth container has no port since it never finished starting.
0.0.0.0:8083
. 8083
0.0.0.0:8082
. 8082
Error: No public port ‘80/tcp’ published for 322f55c7b223
0.0.0.0:8081
. 8081
Scroll back to the beginning of this post to see the output of docker ps a to see the mappings.
Stopping and Removing All Containers
So now we know how the rest of the command works.
Will be expanded to:
docker stop 344bf90e09e7
docker stop 8667dc69816a
docker stop 322f55c7b223
docker stop c5df9ef22d09
docker rm 344bf90e09e7
docker rm 8667dc69816a
docker rm 322f55c7b223
docker rm c5df9ef22d09
Let’s try it on the demo system:
Success! Docker rm echoed the IDs of the containers as it deleted them. Since you can’t delete a running container, the stop commands must have worked.
That’s the nice way to stop and remove a set of containers.
Remove With Extreme Prejudice
There’s a shorter, more concise, and much less friendly way to stop and remove all containers on a system.
Here’s why: In order to stop a container, Docker has to shut down the process running inside it. It does this by sending the application a signal. A signal is a notification to a Linux process that something happened. In this case, the signal means it’s time to shut down.
But not all signals are created equal.
Docker stop sends SIGTERM. Applications have the option to ignore, block, or handle SIGTERM. Well-behaved applications use this opportunity to close any threads or child processes and perform basic house-cleaning tasks. For example, a server application could notify clients that it is going away, or a database could flush any unsaved transactions.
Docker stop will only use SIGKILL if the application does not shut down in a reasonable period of time.
Docker Compose
If you don’t want to spend a lot of time on the command line managing containers, or if you have a set of containers that need to talk to each other, Docker Compose might be a better option than the command line.
Docker Compose uses a YAML configuration file to configure, start, and stop containers. Let’s look at a simple file that starts three containers:
# docker-compose.yml
version: ‘3.7’
services:
one:
image: docker/getting-started
user: root
ports:
— 8081:80
container_name: one
two:
image: docker/getting-started
user: root
ports:
— 8082:80
container_name: two
three:
image: docker/getting-started
user: root
ports:
— 8083:80
container_name: three
Each container is defined as a service. This file defines three containers, named one, two, and three. Like the example above, they run Docker’s getting-started image and map port 80 to 8081, 8082, and 8083, respectively.
Stopping them is just as easy. Simply run docker-compose down in the same directory.
Docker-compose’s output is more user-friendly than docker’s. It stopped all of the containers listed in the file. Docker ps confirms that they are gone.
This is only the tip of the iceberg when it comes to Docker Compose’s capabilities. You can use it to define containers, volumes to store persistent data, access control, private network for containers to communicate over, and much more. CloudBees has a tutorial on how to install and run Jenkins with Docker Compose that demonstrates more of its capabilities.
Wrapping Up: Stopping and Removing Containers
In this post, you saw how to stop and remove all containers on your system with a single command. You learned how to use xargs to tell Docker to run the same command over a set of containers. You also took a look at the nice and not-so-nice ways to shut down a containerized application.
Then we covered Docker Compose and how you can use it to manage a set of containers. You saw how to replace the command line examples we covered with a YAML configuration file and a pair of simple commands.
So, start using these tools to manage your containers today, and take a look at our Docker Compose tutorial for more ideas.
This post was written by Eric Goebelbecker. Eric has worked in the financial markets in New York City for 25 years, developing infrastructure for market data and financial information exchange (FIX) protocol networks. He loves to talk about what makes teams effective (or not so effective!).
Docker Tips: Очистите свою машину от хлама
Привет, Хабр! Представляю вашему вниманию перевод статьи «Docker Tips: Clean Up Your Local Machine» автора Luc Juggery.
Сегодня мы поговорим о том, как Docker использует дисковое пространство хостовой машины, а также разберемся в том, как это пространство освободить от ошметков неиспользуемых образов и контейнеров.
Общее потребление
Docker – крутая штука, наверное сегодня мало кто в этом сомневается. Всего несколько лет назад этот продукт предоставил нам совершенно новый способ построения, доставки и запуска любого окружения, позволяя значительно сэкономить ресурсы процессора и оперативной памяти. В дополнение к этому (а для кого-то это будет даже самым важным) Docker позволил нам невероятно упростить и унифицировать управление жизненным циклом используемых рабочих сред.
Однако, за все эти прелести современной жизни приходится платить. Когда мы запускаем контейнеры, скачиваем или создаем собственные образы, разворачиваем сложные экосистемы, нам приходится платить. И платим мы, в том числе, дисковым пространством.
Если вы никогда не задумывались о том, сколько же места реально занято на вашей машине Docker’ом, то можете быть неприятно удивлены выводом этой команды:
Здесь отображено использование диска Docker’ом в различных разрезах:
Готов поспорить, что уже после этого простого перечисления вы горите желанием почистить диск от мусора и вернуть к жизни драгоценные гигабайты (прим. перев.: особенно, если за эти гигабайты вы ежемесячно перечисляете арендную плату).
Использование диска контейнерами
Каждый раз при создании контейнера на хостовой машине в каталоге /var/lib/docker создается несколько файлов и каталогов, среди которых стоит отметить следующие:
Давайте представим себе систему, на которой установлен девственно чистый Docker, ни разу не участвовавший в запуске контейнеров и сборке образов. Его отчет об использовании дискового пространства будет выглядеть так:
Запустим какой-нибудь контейнер, например, NGINX:
Что происходит с диском:
Судя по выводу, у нас еще нет пространства, которое мы могли бы высвободить. Так как 2 байта это совершенно несерьезно, давайте представим, что наш NGINX неожиданно для всех написал куда-то 100 Мегабайт данных и создал внутри себя файл test.img именно такого размера.
Снова исследуем использование дискового пространства на хосте. Мы увидим, что контейнер (containers) занимает там 100 Мегабайт.
Думаю, ваш пытливый мозг уже задается вопросом, где же находится наш файл test.img. Давайте его поищем:
Не вдаваясь в подробности можно отметить, что файл test.img удобно расположился на уровне чтения-записи, управляемом драйвером overlay2. Если же мы остановим наш контейнер, то хост подскажет нам, что это место, в принципе, можно высвободить:
Как мы можем это сделать? Удалением контейнера, которое повлечет за собой очистку соответствующего пространства на уровне чтения-записи.
С помощью следующей команды вы можете удалить все установленные контейнеры одним махом и очистить ваш диск от всех созданных ими на уровне чтения-записи файлов:
Итак, мы высвободили 104,9 Мегабайта удалением контейнера. Но так как мы уже не используем скачанный ранее образ, то он тоже становится кандидатом на удаление и высвобождение наших ресурсов:
Внимание: до тех пор, пока образ используется хотя бы одним контейнером, вы не сможете использовать этот трюк.
Субкоманда prune, которую мы использовали выше, дает эффект только на остановленных контейнерах. Если мы хотим удалить не только остановленные, но и запущенные контейнеры, следует использовать одну из этих команд:
Использование диска образами
Есть несколько типов образов, которые напрямую не видны конечному пользователю:
Удалить их можно следующим способом:
Мы можем использовать также субкоманду prune:
Если мы вдруг захотим удалить вообще все образы (а не только dangling) одной командой, то можно сделать так:
Использование диска томами
Тома (volumes) применяются для хранения данных за пределами файловой системы контейнера. Например, если мы хотим сохранить результаты работы какого-либо приложения, чтобы использовать их как-то еще. Частым примером являются базы данных.
Давайте запустим контейнер MongoDB, примонтируем к нему внешний по отношению к контейнеру том, и восстановим из него бэкап базы данных (у нас он доступен в файле bck.json):
Данные будут находиться на хостовой машине в каталоге /var/lib/docker/volumes. Но почему не на уровне чтения-записи контейнера? Потому что в Dockerfile образа MongoDB каталог /data/db (в котором MongoDB по умолчанию хранит свои данные) определен как том (volume).
Заметки на полях: многие образы, в результате работы которых должны создаваться данные, используют тома (volumes) для сохранения этих самых данных.
Когда мы наиграемся с MongoDB и остановим (а может даже и удалим) контейнер, том не будет удален. Он продолжит занимать наше драгоценное дисковое пространство до тех пор, пока мы явно не удалим его такой командой:
Ну или мы можем использовать уже знакомую нам субкоманду prune:
Использование диска для кэша сборки образов
В Docker 18.09 процесс создания образов претерпел некоторые изменения благодаря инструменту BuildKit. С помощью этой штуки увеличивается скорость процесса, оптимизируется управление хранением данных и безопасностью. Здесь мы не будем рассматривать все детали этого замечательного инструмента, остановимся лишь нам том, как он затрагивает вопросы использования дискового пространства.
Предположим, что у нас есть совершенно простое приложение Node.Js:
Dockerfile для сборки образа выглядит так:
Давайте соберем образ обычным способом, без использования BuildKit:
Если мы проверим использование дискового пространства, то увидим, что место занимают только базовый образ (node:13-alpine) и конечный образ (app:1.0):
Давайте соберем вторую версию нашего приложения, уже с использованием BuildKit. Для этого нам лишь необходимо установить переменную DOCKER_BUILDKIT в значение 1:
Если мы сейчас проверим использование диска, то увидим, что теперь там участвует кэш сборки (buid-cache):
Для его очистки воспользуемся следующей командой:
Очистить все!
Итак, мы рассмотрели очистку дискового пространства, занятого контейнерами, образами и томами. В этом нам помогает субкоманда prune. Но ее можно использовать и на системном уровне docker, и она очистит все, что только сможет:
Если вы по каким-либо причинам экономите дисковое пространство на машине с Docker, то периодический запуск этой команды стоит ввести в привычку.
Как удалить все Docker образы и контейнеры
Не всегда нужно удалять всё, но объяснение данного «рецепта» объяснит как в целом удалять образы и контейнеры.
Не все Docker-образы одинаково полезны. Они занимают место на диске, найти их на файловой системе не так то просто. К тому же, Docker имеет свои команды для управления образами – так что лучше не лезть самому на файловую систему, а довериться ему – вдруг у него сохранится кеш, или какая-то иная мета-информация, которая будет только путать и его, и вас.
Если кратко, то ответом на поставленный вопрос может служить данный скрипт:
Но давайте не будем на этом останавливаться и рассмотрим подробнее, что здесь происходит!
Получить список имён всех имеющихся Docker-контейнеров
Таким образом, чтобы получить просто список имён всех имеющихся в системе Docker-контейнеров, используется команда:
Непосредственно удаление контейнеров и образов
Сначала нужно остановить запущенные контейнеры – Docker не позволяет удалить контейнер, пока он запущен:
– и пусть вас не смущает, что мы просим остановить уже остановленные контейнеры: вот к этому Docker безразличен. Ты попросил меня остановить то, что и так остановлено? Замечательно! – Значит ничего не надо делать!
Теперь мы можем удалить все контейнеры командой docker rm :
И всё для того, чтобы иметь возможность удалить непосредственно образ. Как вы могли догадаться, удалить образ без удаления всех контейнеров, которые его используют, нельзя.
Вот такой вот аналог смерти кащеевой! А что вы хотели? – Контейнеры.
Об управлении и настройках средства контейнеризации Docker (докер). Команды для настройки и эксплуатации Docker. Настройка сети, сборка образов, запуск программ в контейнере. Запускаем несколько сервисов в одной сети с помощью Docker Compose. Рассматриваем программы для графической настройки докер.
Команды и инструкции терминала (консоли) Linux, MacOS, Windows и прочих операционных систем. Трюки и особенности командных оболочек, скрипты для администрирования Unix. Программирование и скриптование Windows и Linux, тонкая настройка Macos. Консольные команды и их опции, ключи с примерами.
Средства виртуализации, средства управления виртуальными серверами
In this article we will discuss how remove all docker containers or only running or stopped containers.
Suppose we have 6 containers in our docker engine out of which 3 are running and 3 are stopped i.e.
Remove all Running Docker Containers
As we saw above that we have two running containers, now to delete all the running containers use following command,
docker rm command needs IDs or names of the containers to be deleted. But if we want 100 containers to be deleted then it is really hard to type all the container IDs in a single command. Therefore, to make our life easy first we fetched the IDs of all running containers using following command,
It returned the Ids of all running containers i.e.
Then we passed these list of container IDs to docker rm command i.e.
Many times we have large number of stopped containers in our system and we want to delete all of the stopped containers. Let’s see how to do that
Suppose we have total 8 containers out of which 6 are stopped containers i.e. containers with state ‘Exited’ i.e.
Now to delete all the stopped containers use following command,
docker rm command needs IDs or names of the containers to be deleted. But if we want n number of stopped or exited containers to be deleted then it is difficult to pass all the container IDs in a single command. Therefore, to make our life easy first we fetched the IDs of all stopped containers using following command,
Then we passed these list of exited / stopped container IDs to docker rm command i.e.
This is how it removed all stopped containers.
To delete the containers in any specific state, pass that to filter as we did above.
Well there might be situation when we want to delete all the containers i.e. either they are running or stopped or in any other state. For that we can use the following command,
It will basically delete all the containers (both running and stopped).
How to remove docker containers by Image Name
Suppose we have n number of docker containers (both running & stopped). Now we want to delete all the containers by image name.
For that we need to filter the containers by image name, then pass their IDs to docker rm command i.e.
It will delete all the containers of image ‘centos’.
We filtered the containers using image name i.e.
It returned a list of container IDs (both running and stopped) whose image was ‘centos’ i.e.
Now we passed this to docker rm command to delete this containers.
Remove containers using multiple filters
Suppose we want to delete all the containers which are stopped i.e. in exited state and were created using image ‘ubuntu’. Then we will use following command i.e.
It will delete all the containers which are in exited state and were create from ubuntu image. Using this technique we can pass multiple filters while filtering containers for deletion.
How to remove old Docker containers
Maybe there is a directory in which these containers are stored where I can delete them easily manually?
66 Answers 66
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Use the below command to know the Container ID
Then use the below command to stop it.
It contains images auto cleanup, update and monitoring options
You can use some of the Docker UI applications to remove containers.
Sorry for advertisement, but I always use my own application to do the same things. You can try it if you are looking for a simple application to manage Docker images or containers: https://github.com/alex-agency/AMHub.
This is a Docker UI web application which is running inside a Docker container. For installing it, you only need invoke this command:
I am suggesting you to stop the images first and then remove.
You could go like:
You can stop the docker container and once it is stopped you can remove the container.
Stop the container:
Remove the container
If these command do not let you stop/remove the containers, m,ake sure you have sudo access to docker host.