How to remove old and unused Docker images

前端 未结 26 1808
北恋
北恋 2020-11-22 11:28

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 additio

26条回答
  •  鱼传尺愫
    2020-11-22 12:22

    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 '/^/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.

提交回复
热议问题