如何删除 无效的 Docker 镜像? 
2018-06-26 by dongnan
开始之前
为什么会有 <none> 这样命名的镜像?
这些镜像 docker 称为 虚悬镜像,当镜像被新的镜像覆盖时候,老版本镜像名称会变成 <none> 。
例如当前docker宿主机已经存在 nginx:latest 镜像,不久后 docker hub 推送了新版的 nginx 镜像。
当你再次 docker pull nginx:latest 下载镜像时,老版本镜像被覆盖名称也将变成 <none> 。
另外一个需要注意问题的是 从 docker 1.13.1 版本开始引入 docker image 命令,新命令集成了 list、rm、build、tag、push、pull, 等功能,用于替代 images 、build 、rmi 、tag 等二级命令。
考虑到兼容性新版本的 docker 仍然可以使用这些旧的二级子命令,例如 docker pull nginx 与 docker image pull nginx 它们功能都是相同的。
我们需要做的就是找到并删除这些名称带有 <none> 无效镜像。
环境
docker version
Client:
Version:      17.05.0-ce
API version:  1.29
Go version:   go1.7.5
Git commit:   89658be
Built:        Thu May  4 22:06:25 2017
OS/Arch:      linux/amd64
# ...省略
操作步骤
列出带有 <none> 字符的镜像
docker images -f dangling=true | head -n 3
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              d31c5d38836d        3 days ago          1.03GB
<none>              <none>              10d22b8d83b3        6 days ago          1.03GB
删除无效镜像
docker image prune
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y
Deleted Images:
deleted: sha256:d..省略..3e5c4918ee576d729a4b
# ...省略
也可以使用 rmi 命令删除
docker rmi `docker image ls -f dangling=true -q`
命令帮助
docker image
Usage:    docker image COMMAND
Manage images
Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
Run 'docker image COMMAND --help' for more information on a command.
删除镜像命令
docker rmi -h
Flag shorthand -h has been deprecated, please use --help
Usage:    docker rmi [OPTIONS] IMAGE [IMAGE...]
Remove one or more images
Options:
  -f, --force      Force removal of the image
      --no-prune   Do not delete untagged parents
小结
最后来总结下文章中的知识点
- 虚悬镜像,当镜像被新的镜像覆盖时候,老版本镜像名称会变成 <none>。
- 可以使用 docker image prune命令删除 悬壶镜像。
- 对于新同学来说,虽然新旧命令功能相同,但是建议掌握新命令使用方法。