如何删除旧的和未使用的码头图像

发布于 2025-01-22 17:31:53 字数 196 浏览 4 评论 0 原文

长时间运行Docker时,系统中有很多图像。如何一次安全删除所有未使用的Docker图像以释放存储空间?

此外,我还想删除具有正确标签的几个月前拉的图像。

因此,我不是只要求删除未标记的图像。我正在寻找一种删除一般未使用的图像的方法,其中包括未标记的图像和其他图像,例如几个月前使用正确的标签

When running Docker for a long time, there are a lot of images in system. How can I remove all unused Docker images at once safety to free up the storage?

In addition, I also want to remove images pulled months ago, which have the correct TAG.

So, I'm not asking for removing untagged images only. I'm searching for a way to remove general unused images, which includes both untagged and other images such as pulled months ago with correct TAG.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

撩人痒 2025-01-29 17:31:53

(请参阅下文以获取原始答案)


更新2016年9月:Docker 1.13:“ noreferrer”> 26108

docker system prune 将删除所有悬挂数据(容器,网络和图像)。您可以使用 - 卷选项删除所有未使用的卷,并使用 -A 选项删除所有未使用的图像(而不仅仅是悬空)。

您也有:

  • docker Container Prune
  • href =“ https://docs.docker.com/engine/reference/commandline/image_prune/” rel =“ noreferrer”> /docs.docker.com/engine/reference/commandline/network_prune/“ rel =“ noreferrer”> docker network prune
  • docker卷Prune

对于 未使用的图像,使用 docker image prune -a prune -a a (用于删除悬空未汇总的图像)。
警告:'未使用'的意思是“任何容器未引用的图像”:在使用 -A 之前请小心。

a l '答案, Docker System Prune -all 将删除所有未使用的图像,而不仅仅是悬挂的图像……这可能太多了。

docker xxx Prune - noreferrer“> - - 过滤选项可以是限制修剪的好方法( Docker SDK API 1.28最小值,所以Docker 17.04+

当前支持的过滤器是:

  • 之前创建的容器,图像和网络
  • 直到(< timestamp>) - 仅删除给定时间戳 label label =< key&gt) ; label =< key> =< value> label!=< key> ,或 label!=< key&gey> ; =< value> ) - 仅删除使用(或 的)的容器,图像,网络和卷使用)指定的标签。

请参阅“ Prune Images


警告:对于那些 Docker XXX Prune 命令,没有“预览”或“ - Dry-Run ”选项。

moby/moby/cody 第30623页自2017年以来但似乎棘手

出于各种原因,更有代表性的概述将非常复杂;

  • 种族条件(可以通过记录限制来解决);
    在使用“干式运行”时,可能不使用容器/图像/音量/网络,但是在执行实际的修剪的那一刻(或反之亦然),因此干式运行始终是将修剪的“近似”。
  • 更困难的部分是对象(容器,图像,网络等)如何依赖
    例如,如果图像不再有参考(不再使用标签,不再使用它的容器),则可以删除图像。这就是Docker系统修剪以特定顺序删除对象的原因(首先删除所有未使用的容器,然后删除未使用的图像)。
    为了复制“干跑”的相同流程,将需要暂时构建所有对象的表示形式,并根据其引用它们的位置(基本上;基本上;复制所有参考会员,然后从该对象中删除参考文献”阴影“表示)。
  • 最后;在整合 containerd 快照器(图像和图层存储) 的工作中,事情可能会更改;
    例如,图像现在可以是多个架构,并且(待讨论)“修剪”可以从图像中删除未使用的变体(架构)以清理空间,从而带来了另一个维度来计算“可以删除的内容”。 /li>

Original answer (Sep. 2016)

I usually do:

docker rmi $(docker images --filter "dangling=true" -q --no-trunc)

I have an [alias for removing those

晃来= true 过滤器找到未使用的图像

以这种方式找到未使用的图像,删除了标记图像不再引用的任何中间图像。

对于

alias drmae='docker rm $(docker ps -qa --no-trunc --filter "status=exited")'

AS haridsv 指出在评论中

从技术上讲,您应该在清理图像之前首先清理容器,因为这会捕获更多的悬挂图像和更少的错误


jess frazelle(jfrazelle) bashrc函数

dcleanup(){
    docker rm -v $(docker ps --filter status=exited -q 2>/dev/null) 2>/dev/null
    docker rmi $(docker images --filter dangling=true -q 2>/dev/null) 2>/dev/null
}

/A7FD3DF6AB423E6DD04F27727F653753453DB837/.dockerfunc#l8-l8-l8-l8-l8-l8-l8-l1 github.com/spotify/docker-gc“ rel =“ noreferrer”> docker-gc


一个简单的Docker容器和图像垃圾收集脚本。

  • 一个多小时前退出的容器被删除。
  • 删除后不属于剩余容器的图像。

(see below for original answer)


Update Sept. 2016: Docker 1.13: PR 26108 and commit 86de7c0 introduce a few new commands to help facilitate visualizing how much space the docker daemon data is taking on disk and allowing for easily cleaning up "unneeded" excess.

docker system prune will delete all dangling data (containers, networks, and images). You can remove all unused volumes with the --volumes option and remove all unused images (not just dangling) with the -a option.

You also have:

For unused images, use docker image prune -a (for removing dangling and ununsed images).
Warning: 'unused' means "images not referenced by any container": be careful before using -a.

As illustrated in A L's answer, docker system prune --all will remove all unused images not just dangling ones... which can be a bit too much.

Combining docker xxx prune with the --filter option can be a great way to limit the pruning (docker SDK API 1.28 minimum, so docker 17.04+)

The currently supported filters are:

  • until (<timestamp>) - only remove containers, images, and networks created before given timestamp
  • label (label=<key>, label=<key>=<value>, label!=<key>, or label!=<key>=<value>) - only remove containers, images, networks, and volumes with (or without, in case label!=... is used) the specified labels.

See "Prune images" for an example.


Warning: there is no "preview" or "--dry-run" option for those docker xxx prune commands.

This is requested with moby/moby issue 30623 since 2017, but seems tricky to be implemented (Aug. 2022)

Having a more representative overview of what will be pruned will be quite complicated, for various reasons;

  • race conditions (can be resolved by documenting the limitations);
    A container/image/volume/network may not be in use at the time that "dry run" is used, but may be in use the moment the actual prune is executed (or vice-versa), so dry run will always be an "approximation" of what will be pruned.
  • the more difficult part is due to how objects (containers, images, networks etc.) depend on each other.
    For example, an image can be deleted if it no longer has references to it (no more tags, no more containers using it); this is the reason that docker system prune deletes objects in a specific order (first remove all unused containers, then remove unused images).
    In order to replicate the same flow for "dry-run", it will be needed to temporarily construct representation of all objects and where they're referenced based on that (basically; duplicate all reference-counters, and then remove references from that "shadow" representation).
  • Finally; with the work being done on integrating the containerd snapshotter (image and layer store), things may change more;
    For example, images can now be multi-arch, and (to be discussed), "pruning" could remove unused variants (architectures) from an image to clean up space, which brings another dimension to calculating "what can be removed".

Original answer (Sep. 2016)

I usually do:

docker rmi $(docker images --filter "dangling=true" -q --no-trunc)

I have an [alias for removing those dangling images: drmi]13

The dangling=true filter finds unused images

That way, any intermediate image no longer referenced by a labelled image is removed.

I do the same first for exited processes (containers)

alias drmae='docker rm $(docker ps -qa --no-trunc --filter "status=exited")'

As haridsv points out in the comments:

Technically, you should first clean up containers before cleaning up images, as this will catch more dangling images and less errors.


Jess Frazelle (jfrazelle) has the bashrc function:

dcleanup(){
    docker rm -v $(docker ps --filter status=exited -q 2>/dev/null) 2>/dev/null
    docker rmi $(docker images --filter dangling=true -q 2>/dev/null) 2>/dev/null
}

To remove old images, and not just "unreferenced-dangling" images, you can consider docker-gc:


A simple Docker container and image garbage collection script.

  • Containers that exited more than an hour ago are removed.
  • Images that don't belong to any remaining container after that are removed.
奢望 2025-01-29 17:31:53

更新第二个(2017-07-08)

使用更新的 System Prune (再次)(再次),请参阅VONC。不耐烦的人可以使用 -f,-force 选项跳过提示:

docker system prune -f

不耐烦和鲁ckless 可以另外删除“未使用的图像,而不仅仅是悬挂图像” > -a, - all 选项:

docker system prune -af

https://docs.docker .com/Engine/reference/commandline/system_prune/

更新

请参阅 vonc的答案使用最近添加的代码>修剪命令。这是相应的壳牌别名便利:

alias docker-clean=' \
  docker container prune -f ; \
  docker image prune -f ; \
  docker network prune -f ; \
  docker volume prune -f '

旧答案

删除停止(退出)容器:

$ docker ps --no-trunc -aqf "status=exited" | xargs docker rm

删除未使用(悬挂)图像:

$ docker images --no-trunc -aqf "dangling=true" | xargs docker rmi

如果您对进行了 不可撤销的数据丢失 ,然后您可以删除未使用的(悬挂)卷(v1.9及以上):

$ docker volume ls -qf "dangling=true" | xargs docker volume rm

在这里它们处于方便的外壳别名:

alias docker-clean=' \
  docker ps --no-trunc -aqf "status=exited" | xargs docker rm ; \
  docker images --no-trunc -aqf "dangling=true" | xargs docker rmi ; \
  docker volume ls -qf "dangling=true" | xargs docker volume rm'

参考文献

Update the second (2017-07-08)

Refer (again) to VonC, using the even more recent system prune. The impatient can skip the prompt with the -f, --force option:

docker system prune -f

The impatient and reckless can additionally remove "unused images not just the dangling ones" with the -a, --all option:

docker system prune -af

https://docs.docker.com/engine/reference/commandline/system_prune/

Update

Refer to VonC's answer which uses the recently added prune commands. Here is the corresponding shell alias convenience:

alias docker-clean=' \
  docker container prune -f ; \
  docker image prune -f ; \
  docker network prune -f ; \
  docker volume prune -f '

Old answer

Delete stopped (exited) containers:

$ docker ps --no-trunc -aqf "status=exited" | xargs docker rm

Delete unused (dangling) images:

$ docker images --no-trunc -aqf "dangling=true" | xargs docker rmi

If you have exercised extreme caution with regard to irrevocable data loss, then you can delete unused (dangling) volumes (v1.9 and up):

$ docker volume ls -qf "dangling=true" | xargs docker volume rm

Here they are in a convenient shell alias:

alias docker-clean=' \
  docker ps --no-trunc -aqf "status=exited" | xargs docker rm ; \
  docker images --no-trunc -aqf "dangling=true" | xargs docker rmi ; \
  docker volume ls -qf "dangling=true" | xargs docker volume rm'

References

烟雨凡馨 2025-01-29 17:31:53

其他答案很棒,特别是:

docker system prune # doesn't clean out old images
docker system prune --all # cleans out too much

但是我在两个命令的中间需要一些东西,因此 filter 选项是我需要的:

docker image prune --all --filter "until=4320h" # delete images older than 6 months ago; 4320h = 24 hour/day * 30 days/month * 6 months

供参考: https://docs.docker.com/config/config/pruning/#prune-images

The other answers are great, specifically:

docker system prune # doesn't clean out old images
docker system prune --all # cleans out too much

But I needed something in the middle of the two commands so the filter option was what I needed:

docker image prune --all --filter "until=4320h" # delete images older than 6 months ago; 4320h = 24 hour/day * 30 days/month * 6 months

For reference: https://docs.docker.com/config/pruning/#prune-images

薄情伤 2025-01-29 17:31:53

删除旧标记的超过一个月的图像:

$ docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' \
    | grep ' months' | awk '{ print $1 }' \
    | xargs --no-run-if-empty docker rmi

请注意,要删除由存储库中引用的容器使用的图像的失败具有取决于儿童图像...这可能是您想要的。否则只需添加 -f 标志即可。

/etc/cron.daily/docker-gc 脚本的示例:

#!/bin/sh -e

# Delete all stopped containers (including data-only containers).
docker ps -a -q --no-trunc --filter "status=exited" | xargs --no-run-if-empty docker rm -v

# Delete all tagged images more than a month old
# (will fail to remove images still used).
docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' | grep ' months' | awk '{ print $1 }' | xargs --no-run-if-empty docker rmi || true

# Delete all 'untagged/dangling' (<none>) images
# Those are used for Docker caching mechanism.
docker images -q --no-trunc --filter dangling=true | xargs --no-run-if-empty docker rmi

# Delete all dangling volumes.
docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm

To remove old tagged images that are more than a month old:

$ docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' \
    | grep ' months' | awk '{ print $1 }' \
    | xargs --no-run-if-empty docker rmi

Note that it'll fail to remove images that are used by a container, referenced in a repository, has dependent child images... which is probably what you want. Else just add -f flag.

Example of /etc/cron.daily/docker-gc script:

#!/bin/sh -e

# Delete all stopped containers (including data-only containers).
docker ps -a -q --no-trunc --filter "status=exited" | xargs --no-run-if-empty docker rm -v

# Delete all tagged images more than a month old
# (will fail to remove images still used).
docker images --no-trunc --format '{{.ID}} {{.CreatedSince}}' | grep ' months' | awk '{ print $1 }' | xargs --no-run-if-empty docker rmi || true

# Delete all 'untagged/dangling' (<none>) images
# Those are used for Docker caching mechanism.
docker images -q --no-trunc --filter dangling=true | xargs --no-run-if-empty docker rmi

# Delete all dangling volumes.
docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm
无可置疑 2025-01-29 17:31:53

根据 doc ,以下命令将删除超过48小时的图像。

$ docker image prune --all --filter until=48h

According to the doc, the following command will delete images older than 48 hours.

$ docker image prune --all --filter until=48h
铁憨憨 2025-01-29 17:31:53

假设您有 docker 1.13 或更高的您只能使用Prune命令。对于专门用于删除旧图像的问题,您想要第一个。

# Remove unused images
docker image prune

# Remove stopped containers.
docker container prune

# Remove unused volumes
docker volume prune

# Remove unused networks
docker network prune

# Command to run all prunes:
docker system prune

我建议不要习惯使用 docker System Prune 命令。我认为用户会不小心删除他们并不是故意的事情。就个人而言,我将主要使用 Docker Image Prune Docker Container Prune 命令。

Assuming you have Docker 1.13 or higher you can just use the prune commands. For your question specifically for removing old images, you want the first one.

# Remove unused images
docker image prune

# Remove stopped containers.
docker container prune

# Remove unused volumes
docker volume prune

# Remove unused networks
docker network prune

# Command to run all prunes:
docker system prune

I would recommend not getting used to using the docker system prune command. I reckon users will accidentally remove things they don't mean to. Personally, I'm going to mainly be using the docker image prune and docker container prune commands.

寄意 2025-01-29 17:31:53

到目前为止(Docker版本1.12)我们使用以下命令来删除所有运行的容器。另外,如果要删除卷,我们可以在以下命令中使用其各自的标签-v手动执行此操作。

删除所有退出的容器

docker rm $(docker ps -q -f status=exited)

删除所有停止的容器

docker rm $(docker ps -a -q)

删除所有运行和停止容器

docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)

删除所有容器,没有任何条件,

docker container rm $(docker container ps -aq)

但是,在版本1.13及更高版本中,要进行完整的系统和清理,我们可以直接用户以下命令:

docker system prune

所有未使用的容器,图像,网络和卷都将被删除。我们还可以使用以下命令来完成此操作,以清理各个组件:

docker container prune
docker image prune
docker network prune
docker volume prune

Until now (Docker version 1.12) we are using the following command to delete all the running containers. Also, if we want to delete the volumes, we can do that manually using its respective tag -v in the following command.

Delete all Exited Containers

docker rm $(docker ps -q -f status=exited)

Delete all Stopped Containers

docker rm $(docker ps -a -q)

Delete All Running and Stopped Containers

docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)

Remove all containers, without any criteria

docker container rm $(docker container ps -aq)

But, in version 1.13 and above, for complete system and cleanup, we can directly user the following command:

docker system prune

All unused containers, images, networks and volumes will get deleted. We can also do this using the following commands that clean up the individual components:

docker container prune
docker image prune
docker network prune
docker volume prune
阳光下的泡沫是彩色的 2025-01-29 17:31:53

这对我有用:

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

This worked for me:

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")
韵柒 2025-01-29 17:31:53

我最近写了一个脚本来解决我的一台服务器:

#!/bin/bash

# Remove all the dangling images
DANGLING_IMAGES=$(docker images -qf "dangling=true")
if [[ -n $DANGLING_IMAGES ]]; then
    docker rmi "$DANGLING_IMAGES"
fi

# Get all the images currently in use
USED_IMAGES=($( \
    docker ps -a --format '{{.Image}}' | \
    sort -u | \
    uniq | \
    awk -F ':' '$2{print $1":"$2}!$2{print $1":latest"}' \
))

# Get all the images currently available
ALL_IMAGES=($( \
    docker images --format '{{.Repository}}:{{.Tag}}' | \
    sort -u \
))

# Remove the unused images
for i in "${ALL_IMAGES[@]}"; do
    UNUSED=true
    for j in "${USED_IMAGES[@]}"; do
        if [[ "$i" == "$j" ]]; then
            UNUSED=false
        fi
    done
    if [[ "$UNUSED" == true ]]; then
        docker rmi "$i"
    fi
done

I recently wrote a script to solve this on one of my servers:

#!/bin/bash

# Remove all the dangling images
DANGLING_IMAGES=$(docker images -qf "dangling=true")
if [[ -n $DANGLING_IMAGES ]]; then
    docker rmi "$DANGLING_IMAGES"
fi

# Get all the images currently in use
USED_IMAGES=($( \
    docker ps -a --format '{{.Image}}' | \
    sort -u | \
    uniq | \
    awk -F ':' '$2{print $1":"$2}!$2{print $1":latest"}' \
))

# Get all the images currently available
ALL_IMAGES=($( \
    docker images --format '{{.Repository}}:{{.Tag}}' | \
    sort -u \
))

# Remove the unused images
for i in "${ALL_IMAGES[@]}"; do
    UNUSED=true
    for j in "${USED_IMAGES[@]}"; do
        if [[ "$i" == "$j" ]]; then
            UNUSED=false
        fi
    done
    if [[ "$UNUSED" == true ]]; then
        docker rmi "$i"
    fi
done
负佳期 2025-01-29 17:31:53

这是一个清理Docker图像并收回空间的脚本。

#!/bin/bash -x
## Removing stopped container
docker ps -a | grep Exited | awk '{print $1}' | xargs docker rm

## If you do not want to remove all container you can have filter for days and weeks old like below
#docker ps -a | grep Exited | grep "days ago" | awk '{print $1}' | xargs docker rm
#docker ps -a | grep Exited | grep "weeks ago" | awk '{print $1}' | xargs docker rm

## Removing Dangling images
## There are the layers images which are being created during building a Docker image. This is a great way to recover the spaces used by old and unused layers.

docker rmi $(docker images -f "dangling=true" -q)

## Removing images of perticular pattern For example
## Here I am removing images which has a SNAPSHOT with it.

docker rmi $(docker images | grep SNAPSHOT | awk '{print $3}')

## Removing weeks old images

docker images | grep "weeks ago" | awk '{print $3}' | xargs docker rmi

## Similarly you can remove days, months old images too.

原始脚本

https://github.com/vishalvsh1/docker-image-image-cleanup

通常将所有临时文件与图像构建和图层相关,

/var/lib/docker

此路径是系统的本地路径,通常在根分区, “/”/“”

您可以安装较大的磁盘空间,并将/var/lib/docker 的内容移至新的安装位置,并创建一个符号链接。

这样,即使Docker图像占据了空间,也不会影响您的系统,因为它将使用其他安装位置。

原始文章: 管理Docker Images在本地磁盘上

Here is a script to clean up Docker images and reclaim the space.

#!/bin/bash -x
## Removing stopped container
docker ps -a | grep Exited | awk '{print $1}' | xargs docker rm

## If you do not want to remove all container you can have filter for days and weeks old like below
#docker ps -a | grep Exited | grep "days ago" | awk '{print $1}' | xargs docker rm
#docker ps -a | grep Exited | grep "weeks ago" | awk '{print $1}' | xargs docker rm

## Removing Dangling images
## There are the layers images which are being created during building a Docker image. This is a great way to recover the spaces used by old and unused layers.

docker rmi $(docker images -f "dangling=true" -q)

## Removing images of perticular pattern For example
## Here I am removing images which has a SNAPSHOT with it.

docker rmi $(docker images | grep SNAPSHOT | awk '{print $3}')

## Removing weeks old images

docker images | grep "weeks ago" | awk '{print $3}' | xargs docker rmi

## Similarly you can remove days, months old images too.

Original script

https://github.com/vishalvsh1/docker-image-cleanup

Usually Docker keeps all temporary files related to image building and layers at

/var/lib/docker

This path is local to the system, usually at THE root partition, "/".

You can mount a bigger disk space and move the content of /var/lib/docker to the new mount location and make a symbolic link.

This way, even if Docker images occupy space, it will not affect your system as it will be using some other mount location.

Original post: Manage Docker images on local disk

双马尾 2025-01-29 17:31:53

我正在使用此命令:

export BEFORE_DATETIME=$(date --date='10 weeks ago' +"%Y-%m-%dT%H:%M:%S.%NZ")
docker images -q | while read IMAGE_ID; do
    export IMAGE_CTIME=$(docker inspect --format='{{.Created}}' --type=image ${IMAGE_ID})
    if [[ "${BEFORE_DATETIME}" > "${IMAGE_CTIME}" ]]; then
        echo "Removing ${IMAGE_ID}, ${BEFORE_DATETIME} is earlier then ${IMAGE_CTIME}"
        docker rmi -f ${IMAGE_ID};
    fi;
done

这将删除所有创建时间大于10周前的图像。

I'm using this command:

export BEFORE_DATETIME=$(date --date='10 weeks ago' +"%Y-%m-%dT%H:%M:%S.%NZ")
docker images -q | while read IMAGE_ID; do
    export IMAGE_CTIME=$(docker inspect --format='{{.Created}}' --type=image ${IMAGE_ID})
    if [[ "${BEFORE_DATETIME}" > "${IMAGE_CTIME}" ]]; then
        echo "Removing ${IMAGE_ID}, ${BEFORE_DATETIME} is earlier then ${IMAGE_CTIME}"
        docker rmi -f ${IMAGE_ID};
    fi;
done

This will remove all images whose creation time is greater than 10 weeks ago.

心作怪 2025-01-29 17:31:53

如果您想删除数月前删除 x 的图像,则可以尝试以下示例,该示例删除三个月前创建的图像:

three_months_old_images=`docker images | grep -vi "<none>" | tr -s ' ' | cut -d" " -f3,4,5,6 | grep "3 months ago" | cut -d" " -f1`
docker rmi $three_months_old_images

If you want to remove images pulled X months ago, you can try the below example which remove images created three months ago:

three_months_old_images=`docker images | grep -vi "<none>" | tr -s ' ' | cut -d" " -f3,4,5,6 | grep "3 months ago" | cut -d" " -f1`
docker rmi $three_months_old_images
妳是的陽光 2025-01-29 17:31:53

修剪所有图像和卷
Docker System Prune -af -Volumes

To prune all images and volumes as well
docker system prune -af --volumes

我一直都在从未离去 2025-01-29 17:31:53

由于您已经有很长的时间跑了很长时间,因此可能有各种物品占用空间,而不仅仅是图像。找出使用该空间的方法:
Docker System DF 请参阅docs

在我的情况下大部分是由“构建缓存”使用的,将其删除:
Docker Builder Prune 请参阅文档

Since you've had docker running for a long time there might be various items taking up space, not just images. To find out what is using the space:
docker system df see docs

In my case most of it was used by "Build cache", to remove it:
docker builder prune see docs

千纸鹤带着心事 2025-01-29 17:31:53

Docker System Prune -A

(您被要求确认命令。如果您知道自己在做什么,请使用 -f 强制运行。)

docker system prune -a

(You'll be asked to confirm the command. Use -f to force run, if you know what you're doing.)

长安忆 2025-01-29 17:31:53

@vonc已经给出了一个很好的答案,但是对于完整性来说,这是我一直在使用的一些脚本---也可以在任何差事的码头流程中添加一些脚本:

#!/bin/bash

imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
   echo docker rmi ${imgs}
   docker rmi ${imgs}
else
   echo "No images to remove"
fi

procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
   echo docker rm ${procs}
   docker rm ${procs}
else
   echo "No processes to purge"
fi

@VonC already gave a very nice answer, but for completeness here is a little script I have been using---and which also nukes any errand Docker processes should you have some:

#!/bin/bash

imgs=$(docker images | awk '/<none>/ { print $3 }')
if [ "${imgs}" != "" ]; then
   echo docker rmi ${imgs}
   docker rmi ${imgs}
else
   echo "No images to remove"
fi

procs=$(docker ps -a -q --no-trunc)
if [ "${procs}" != "" ]; then
   echo docker rm ${procs}
   docker rm ${procs}
else
   echo "No processes to purge"
fi
甲如呢乙后呢 2025-01-29 17:31:53

要删除未运行容器的标记图像,您将必须使用一个小脚本:

#!/bin/bash

# remove not running containers
docker rm $(docker ps -f "status=exited" -q)

declare -A used_images

# collect images which has running container
for image in $(docker ps | awk 'NR>1 {print $2;}'); do
    id=$(docker inspect --format="{{.Id}}" $image);
    used_images[$id]=$image;
done

# loop over images, delete those without a container
for id in $(docker images --no-trunc -q); do
    if [ -z ${used_images[$id]} ]; then
        echo "images is NOT in use: $id"
        docker rmi $id
    else
        echo "images is in use:     ${used_images[$id]}"
    fi
done

To remove tagged images which have not container running, you will have to use a little script:

#!/bin/bash

# remove not running containers
docker rm $(docker ps -f "status=exited" -q)

declare -A used_images

# collect images which has running container
for image in $(docker ps | awk 'NR>1 {print $2;}'); do
    id=$(docker inspect --format="{{.Id}}" $image);
    used_images[$id]=$image;
done

# loop over images, delete those without a container
for id in $(docker images --no-trunc -q); do
    if [ -z ${used_images[$id]} ]; then
        echo "images is NOT in use: $id"
        docker rmi $id
    else
        echo "images is in use:     ${used_images[$id]}"
    fi
done
耳钉梦 2025-01-29 17:31:53

几周前卸下旧容器。

docker rm $(docker ps -a | grep“ weeks” | awk'{print $ 1;}')

几周前删除旧图像。当心。这将删除几周前创建的基本图像,但您的新图像可能正在使用。

docker rmi $(docker images | grep'weeks'| awk'{print $ 3;}')>

Remove old containers weeks ago.

docker rm $(docker ps -a | grep "weeks" | awk '{ print $1; }')

Remove old images weeks ago. Be careful. This will remove base images which was created weeks ago but which your new images might be using.

docker rmi $(docker images | grep 'weeks' | awk '{ print $3; }')

牛↙奶布丁 2025-01-29 17:31:53

如何删除标记的图像

  1. docker rmi标签首先

  2. docker rmi rmi图像。

    #可以在一个Docker RMI调用中完成的
    Docker rmi&lt; repo:tag&gt; &lt; imageId&gt;

(这项工作2016年11月,Docker版本1.12.2)

例如

$ docker images 
REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
usrxx/the-application   16112805            011fd5bf45a2        12 hours ago        5.753 GB
usryy/the-application   vx.xx.xx            5af809583b9c        3 days ago          5.743 GB
usrzz/the-application   vx.xx.xx            eef00ce9b81f        10 days ago         5.747 GB
usrAA/the-application   vx.xx.xx            422ba91c71bb        3 weeks ago         5.722 GB
usrBB/the-application   v1.00.18            a877aec95006        3 months ago        5.589 GB

$ docker rmi usrxx/the-application:16112805 && docker rmi 011fd5bf45a2
$ docker rmi usryy/the-application:vx.xx.xx && docker rmi 5af809583b9c
$ docker rmi usrzz/the-application:vx.xx.xx eef00ce9b81f
$ docker rmi usrAA/the-application:vx.xx.xx 422ba91c71bb
$ docker rmi usrBB/the-application:v1.00.18 a877aec95006

,脚本删除了2周以上的任何东西。

IMAGESINFO=$(docker images --no-trunc --format '{{.ID}} {{.Repository}} {{.Tag}} {{.CreatedSince}}' |grep -E " (weeks|months|years)")
TAGS=$(echo "$IMAGESINFO" | awk '{ print $2 ":" $3 }' )
IDS=$(echo "$IMAGESINFO" | awk '{ print $1 }' )
echo remove old images TAGS=$TAGS IDS=$IDS
for t in $TAGS; do docker rmi $t; done
for i in $IDS; do docker rmi $i; done

How to remove a tagged image

  1. docker rmi the tag first

  2. docker rmi the image.

    # that can be done in one docker rmi call e.g.: #
    docker rmi <repo:tag> <imageid>

(this works Nov 2016, Docker version 1.12.2)

e.g.

$ docker images 
REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
usrxx/the-application   16112805            011fd5bf45a2        12 hours ago        5.753 GB
usryy/the-application   vx.xx.xx            5af809583b9c        3 days ago          5.743 GB
usrzz/the-application   vx.xx.xx            eef00ce9b81f        10 days ago         5.747 GB
usrAA/the-application   vx.xx.xx            422ba91c71bb        3 weeks ago         5.722 GB
usrBB/the-application   v1.00.18            a877aec95006        3 months ago        5.589 GB

$ docker rmi usrxx/the-application:16112805 && docker rmi 011fd5bf45a2
$ docker rmi usryy/the-application:vx.xx.xx && docker rmi 5af809583b9c
$ docker rmi usrzz/the-application:vx.xx.xx eef00ce9b81f
$ docker rmi usrAA/the-application:vx.xx.xx 422ba91c71bb
$ docker rmi usrBB/the-application:v1.00.18 a877aec95006

e.g. Scripted remove anything older than 2 weeks.

IMAGESINFO=$(docker images --no-trunc --format '{{.ID}} {{.Repository}} {{.Tag}} {{.CreatedSince}}' |grep -E " (weeks|months|years)")
TAGS=$(echo "$IMAGESINFO" | awk '{ print $2 ":" $3 }' )
IDS=$(echo "$IMAGESINFO" | awk '{ print $1 }' )
echo remove old images TAGS=$TAGS IDS=$IDS
for t in $TAGS; do docker rmi $t; done
for i in $IDS; do docker rmi $i; done
变身佩奇 2025-01-29 17:31:53
docker rm $(docker ps -faq)
docker rmi $(docker ps -faq)

-f力

-a all

-q在模式下

docker rm $(docker ps -faq)
docker rmi $(docker ps -faq)

-f force

-a all

-q in the mode

久隐师 2025-01-29 17:31:53

首先,运行 Docker Images 以查看图像列表,并将图像哈希ID复制到剪贴板中。

运行 Docker RMI -F&lt; image&gt;

记住选项 -f 是强制删除。

First, run docker images to see list of images and copy IMAGE HASH ID into clipboard.

Run docker rmi -f <Image>

Remember option -f is force deleting.

第七度阳光i 2025-01-29 17:31:53

有时我会遇到Docker会分配并继续使用磁盘空间的问题,即使没有将空间分配给任何特定图像或现有容器。我意外地生成此问题的最新方式是在RHEL 7.1中使用“ Docker-engine” Centos构建而不是“ Docker”。似乎发生的事情有时是容器清理未能成功完成,因此空间永远不会重复使用。当80GB驱动器分配为/时,我必须提出一种创造性的方法来解决问题。

这是我想到的。首先解决磁盘完整错误:

  1. 停止Docker: SytemCtl停止Docker

  2. 分配了一个新驱动器,如SAS /mnt/docker

  3. /var/lib/docker中的所有文件移动到/mnt/docker 。我使用了命令:

      rsync -aphsx -e-remove-source-files/var/lib/docker//mnt/docker/
     

  4. 将新驱动器安装到/var/lib/docker

在这一点上,我不再有磁盘完全错误,但是我仍在浪费大量空间。接下来的步骤是要解决这个问题。

  1. 开始Docker: SytemCtl开始Docker

  2. 保存所有图像:

      docker save $(docker images | sed -e'/^&lt; none&gt;/d'-e'/^repository/d''-e's,[] [] [] []*,:,:,' -   - e's,[]。*,,')&gt; /root/docker.img
     
  3. 卸载Docker。

  4. /var/lib/docker 中删除所有内容:

      rm -rf/var/lib/docker/[cdintv]*
     
  5. 重新安装docker

  6. 启用Docker: Systemctl启用Docker

  7. start docker: systemctl start docker

  8. 还原图像:

      docker Load&lt; /root/docker.img
     
  9. 启动您需要运行的任何持久容器。

这使我的磁盘用法从67 GB的Docker降至Docker的6 GB。

我不建议您每天使用。但是,当Docker似乎已经失去了对软件错误或意外重启的途径时,运行很有用。

Occasionally I have run into issues where Docker will allocate and continue to use disk space, even when the space is not allocated to any particular image or existing container. The latest way I generated this issue accidentally was using "docker-engine" centos build instead of "docker" in RHEL 7.1. What seems to happen is sometimes the container clean-ups are not completed successfully and then the space is never reused. When the 80GB drive I allocated as / was filled with /var/lib/docker files I had to come up with a creative way to resolve the issue.

Here is what I came up with. First to resolve the disk full error:

  1. Stop docker: systemctl stop docker

  2. Allocated a new drive mounted as say /mnt/docker .

  3. Move all the files in /var/lib/docker to /mnt/docker . I used the command:

    rsync -aPHSx --remove-source-files /var/lib/docker/ /mnt/docker/
    
  4. Mount the new drive to /var/lib/docker.

At this point I no longer had a disk full error, but I was still wasting a huge amount of space. The next steps are to take care of that.

  1. Start Docker: systemctl start docker

  2. Save the all the images:

    docker save $(docker images |sed -e '/^<none>/d' -e '/^REPOSITORY/d' -e 's,[ ][ ]*,:,' -e 's,[ ].*,,') > /root/docker.img
    
  3. Uninstall docker.

  4. Erase everything in /var/lib/docker:

    rm -rf /var/lib/docker/[cdintv]*
    
  5. Reinstall docker

  6. Enable docker: systemctl enable docker

  7. Start docker: systemctl start docker

  8. Restore images:

    docker load < /root/docker.img
    
  9. Start any persistent containers you need running.

This dropped my disk usage from 67 GB for docker to 6 GB for docker.

I do not recommend this for everyday use. But it is useful to run when it looks like docker has lost track of used disk space do to software errors, or unexpected reboots.

浅唱々樱花落 2025-01-29 17:31:53
docker rm `docker ps -aq`

或者

docker rm $(docker ps -q -f status=exited)
docker rm `docker ps -aq`

or

docker rm $(docker ps -q -f status=exited)
悲喜皆因你 2025-01-29 17:31:53

如果您希望自动/定期清理退出的容器,并删除运行容器未使用的图像和量,则可以下载图像 Meltwater/Docker-Cleanup

刚运行:

docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw  -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest

默认情况下每30分钟运行一次。但是,您可以在秒内使用此标志(delay_time = 1800选项)来设置延迟时间。

更多详细信息: https://github.com/meltwater/meltwater/meltwater/docker-cleanup/docker-cleanup-cleanup- /blob/master/readme.md

If you wish to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the image meltwater/docker-cleanup.

Just run:

docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw  -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest

It runs every 30 minutes by default. You can however set the delay time by using this flag in seconds (DELAY_TIME=1800 option).

More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md

森林很绿却致人迷途 2025-01-29 17:31:53

如果您自己构建这些修剪的图像(来自其他一些较旧的基本图像),请谨慎使用基于 docker image prune 的上述可接受的解决方案,因为该命令是钝的,并且会尝试删除所有依赖项您的最新图像要求(命令可能应重命名为 Docker Image* S* Prune )。

我为Docker Image构建管道提出的解决方案(在 yyyymmdd 格式中,有每日构建和标签=日期)是:

# carefully narrow down the image to be deleted (to avoid removing useful static stuff like base images)
my_deleted_image=mirekphd/ml-cpu-py37-vsc-cust

# define the monitored image (tested for obsolescence), which will be usually the same as deleted one, unless deleting some very infrequently built image which requires a separate "clock"
monitored_image=mirekphd/ml-cache

# calculate the oldest acceptable tag (date)
date_week_ago=$(date -d "last week" '+%Y%m%d')

# get the IDs of obsolete tags of our deleted image
# note we use monitored_image to test for obsolescence
my_deleted_image_obsolete_tag_ids=$(docker images --filter="before=$monitored_image:$date_week_ago" | grep $my_deleted_image | awk '{print $3}')

# remove the obsolete tags of the deleted image
# (note it typically has to be forced using -f switch)
docker rmi -f $my_deleted_image_obsolete_tag_ids

If you build these pruned images yourself (from some other, older base images) please be careful with the accepted solutions above based on docker image prune, as the command is blunt and will try to remove also all dependencies required by your latest images (the command should be probably renamed to docker image*s* prune).

The solution I came up for my docker image build pipelines (where there are daily builds and tags=dates are in the YYYYMMDD format) is this:

# carefully narrow down the image to be deleted (to avoid removing useful static stuff like base images)
my_deleted_image=mirekphd/ml-cpu-py37-vsc-cust

# define the monitored image (tested for obsolescence), which will be usually the same as deleted one, unless deleting some very infrequently built image which requires a separate "clock"
monitored_image=mirekphd/ml-cache

# calculate the oldest acceptable tag (date)
date_week_ago=$(date -d "last week" '+%Y%m%d')

# get the IDs of obsolete tags of our deleted image
# note we use monitored_image to test for obsolescence
my_deleted_image_obsolete_tag_ids=$(docker images --filter="before=$monitored_image:$date_week_ago" | grep $my_deleted_image | awk '{print $3}')

# remove the obsolete tags of the deleted image
# (note it typically has to be forced using -f switch)
docker rmi -f $my_deleted_image_obsolete_tag_ids
笑饮青盏花 2025-01-29 17:31:53

=的官方参考

请参阅将删除:

  • 所有停止的容器的
  • 所有网络至少一个容器所有的网络
  • 所有悬挂图像
  • 所有构建cache

docker system prune -a 都会做同样的事情,但是除了删除所有悬挂图像,它将更广泛地删除:

  • 所有图像没有至少一个与它们关联的容器

什么是悬空的图像?

docker图像由多层包装在父母的容器层中``当从dockerfile生成整体容器图像时。悬空的图像是与任何其他标记的图像没有关系的层,因此在构建的任何新容器中都不会使用任何用途。他们不再有目的并消耗磁盘空间。

例如,可以通过以下过程创建悬空图像:

构建一个命名映像 my-image 从dockerfile构建,而无需指定任何标签:

FROM ubuntu:latest
CMD ["echo", "Hello World"]

docker build -t my-image

docker images

REPOSITORY   TAG       IMAGE ID
my-image     latest    7ed6e7202eca   <--- created, not dangling
ubuntu       latest    825d55fb6340

更新dockerfile:< /em>

FROM ubuntu:latest
CMD ["echo", "Hello, World!"]

重建图像重复使用上一个名称,而无需指定任何标签:

docker build -t my-image

docker images

REPOSITORY   TAG       IMAGE ID
my-image     latest    da6e74196f66   <--- replacement layer
<none>       <none>    7ed6e7202eca   <--- previous layer, now dangling
ubuntu       latest    825d55fb6340

构建创建了一个新的 my-image layer。如我们所见,最初创建的图层仍然存在,但其名称和标签设置为&lt; none&gt;:&lt; none&gt; 。该层永远不可能与任何Docker容器层关联,这意味着它是“悬空”

什么是没有至少一个容器的图像?

未使用的图像意味着它没有被分配或在容器中使用。例如, docker ps -a 将列出您的所有运行和停止容器。这些容器中的任何一个都使用的任何图像都是“使用的图像”。

运行Docker System Prune -a时,它将删除未使用的图像和悬空图像。与其至少一个容器相关的任何图像都不会受到影响。

See the official reference for docker system prune

docker system prune will remove:

  • all stopped containers
  • all networks not used by at least one container
  • all dangling images
  • all build cache

docker system prune -a will do the same, but in additional to removing all dangling images, it will more broadly remove:

  • all images without at least one container associated to them

What are dangling images?

Docker images consist of multiple layers that get wrapped inside a parent 'container layer' when the overall container image is generated from a Dockerfile. Dangling images are layers that have no relationship to any other tagged images, and will therefore never have any use within any new containers that are built. They no longer serve a purpose and consume disk space.

For example a dangling image can be created by the following process:

Build a named image my-image from Dockerfile, without specifying any tag:

FROM ubuntu:latest
CMD ["echo", "Hello World"]

docker build -t my-image

docker images

REPOSITORY   TAG       IMAGE ID
my-image     latest    7ed6e7202eca   <--- created, not dangling
ubuntu       latest    825d55fb6340

Update the Dockerfile:

FROM ubuntu:latest
CMD ["echo", "Hello, World!"]

Rebuild image re-using the previous name, without specifying any tag:

docker build -t my-image

docker images

REPOSITORY   TAG       IMAGE ID
my-image     latest    da6e74196f66   <--- replacement layer
<none>       <none>    7ed6e7202eca   <--- previous layer, now dangling
ubuntu       latest    825d55fb6340

The build created a new my-image layer. As we can see, the layer that was originally created is still there, but its name and tag are set to <none>:<none>. It will never be possible for this layer to be associated with any docker container layer, which means it's 'dangling'

What are images without at least one container associated to them?

An unused image means that it has not been assigned or used in a container. For example, docker ps -a will list all of your running and stopped containers. Any image being used by any of these containers is a "used image".

When running docker system prune -a, it will remove both unused and dangling images. Any image with at least one container associated to it will not be affected.

乖乖 2025-01-29 17:31:53

有麻雀插件 docker-remove-dangangling-images 您可以用来清洁上下停止的容器和未使用的(悬挂)图像:

$ SPARROW PLG运行Docker-remove-dangling-Images

它既适用于Linux和Windows OS。

There is sparrow plugin docker-remove-dangling-images you can use to clean up stopped containers and unused (dangling) images:

$ sparrow plg run docker-remove-dangling-images

It works both for Linux and Windows OS.

执笏见 2025-01-29 17:31:53

如果您有很多,那么它可能真的很繁琐,但要删除它们,但是幸运的是,我们Docker有一些命令可以帮助我们消除悬挂的图像。在Docker的较旧版本中(并且今天仍然有效),您可以通过运行 docker rmi -f $(docker&nbsp; images&nbsp; -f“ dandling = true” -q)删除悬挂图像&nbsp;代码>。

If you have a lot of them, it can be really tedious to remove them, but lucky for us Docker has a few commands to help us eliminate dangling images. In older versions of Docker (and this still works today), you can delete dangling images on their own by running docker rmi -f $(docker images -f "dangling=true" -q) .

淡莣 2025-01-29 17:31:53

我通常会做 Docker RM -F $(Docker PS -A -Q) Docker System Prune 以清除所有悬挂容器。

I usually do docker rm -f $(docker ps -a -q) and docker system prune to purge all dangling containers.

扶醉桌前 2025-01-29 17:31:53

一个尚未删除所有容器的解决方案:

Docker PS -A |切割-d''-f 1 | Xargs Docker RM

剪切-d''-f 1 返回所有容器的ID。

One yet solution for removing all containers:

docker ps -a | cut -d ' ' -f 1 | xargs docker rm

cut -d ' ' -f 1 returns all containers' IDs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文