├── .dockerignore ├── .github ├── ISSUE_TEMPLATE.md └── stale.yml ├── .travis.yml ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Makefile.docker ├── README.md ├── debian ├── .gitignore ├── changelog ├── compat ├── control ├── dirs ├── install └── rules ├── docker-gc ├── rpm ├── .gitignore ├── Makefile └── docker-gc.spec ├── tests ├── run-tests.sh └── test-volume-removal.sh └── version.txt /.dockerignore: -------------------------------------------------------------------------------- 1 | .git/ 2 | debian/ 3 | 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | [Add feature/bug description here] 4 | 5 | ## How to reproduce 6 | 7 | [Add steps on how to reproduce this issue] 8 | 9 | ## What do you expect 10 | 11 | [Describe what do you expect to happen] 12 | 13 | ## What happened instead 14 | 15 | [Describe the actual results] 16 | 17 | ## Software: 18 | 19 | - bash version: [Add bash version here] 20 | 21 | ## Full backtrace 22 | 23 | ```text 24 | [Paste full backtrace here] 25 | ``` 26 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | daysUntilStale: 60 2 | daysUntilClose: 7 3 | exemptLabels: 4 | - pinned 5 | - security 6 | staleLabel: stale 7 | markComment: > 8 | This issue has been automatically marked as stale because it has not had 9 | recent activity. It will be closed if no further activity occurs. Thank you 10 | for your contributions. 11 | closeComment: false 12 | only: issues 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: generic 2 | script: sudo ./tests/run-tests.sh 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 4 | ## Response Times 5 | 6 | This project is developed and maintained by an infrastructure team at Spotify. Lots of teams at 7 | Spotify use relatively recent versions of this project in production for mission-critical systems. 8 | 9 | That being said, this is our day job where our primary users are our colleagues. 10 | So we might be slow in getting back to you because we're busy working on Spotify-specific things 11 | or because your issues are being prioritized behind those of our colleagues. 12 | 13 | Please poke us if you feel you're being neglected, and we'll do our best to get back to you. 14 | 15 | ## Related Tools You May Find Useful 16 | 17 | If you like this project, you might also like [Helios][2], [docker-client][3], [docker-maven-plugin][4], 18 | [helios-skydns][5], and [helios-consul][6]. 19 | 20 | ## Reporting Bugs 21 | 22 | Please make sure you're using the latest version. This project is 23 | released continuously as it's developed so new releases come out almost as frequently as we 24 | commit to master. 25 | 26 | ## Contributing 27 | 28 | Before creating a new issue, see if there's already an existing issue. 29 | 30 | If you create a minor bugfix, feel free to submit a PR. 31 | If your PR is for a significant change or a new feature, feel free to ask for our feedback 32 | before writing code to check we're on the same page. 33 | 34 | [2]: https://github.com/spotify/helios 35 | [3]: https://github.com/spotify/docker-client 36 | [4]: https://github.com/spotify/docker-maven-plugin 37 | [5]: https://github.com/spotify/helios-skydns 38 | [6]: https://github.com/spotify/helios-consul 39 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.10 2 | 3 | ENV DOCKER_VERSION 18.09.6 4 | 5 | RUN apk --no-cache add bash \ 6 | && wget -q https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz \ 7 | && tar zxf docker-${DOCKER_VERSION}.tgz \ 8 | && mv docker/docker /usr/local/bin/ \ 9 | && rm -rf docker/ docker-${DOCKER_VERSION}.tgz 10 | 11 | COPY ./docker-gc /docker-gc 12 | 13 | VOLUME /var/lib/docker-gc 14 | 15 | CMD ["/docker-gc"] 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile.docker: -------------------------------------------------------------------------------- 1 | DOCKER_REPOSITORY ?= spotify/docker-gc 2 | DOCKER_TAG ?= $(shell cat version.txt) 3 | 4 | DOCKER ?= docker 5 | export DOCKER 6 | 7 | .PHONY: all image push 8 | 9 | image: 10 | $(DOCKER) build -t $(DOCKER_REPOSITORY):$(DOCKER_TAG) . 11 | 12 | push: image 13 | $(DOCKER) push $(DOCKER_REPOSITORY):$(DOCKER_TAG) 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # docker-gc 2 | 3 | [![Build Status](https://travis-ci.com/spotify/docker-gc.svg?branch=master)](https://travis-ci.com/spotify/docker-gc) 4 | [![License](https://img.shields.io/github/license/spotify/docker-client.svg)](LICENSE) 5 | 6 | ## Status: mature 7 | 8 | **We're not developing or accepting new features.** 9 | 10 | Consider using [`docker system prune`][prune] instead. 11 | 12 | 13 | * [Building](#building) 14 | * [Installing](#installing) 15 | * [Usage](#usage) 16 | * [Excluding Images From Garbage Collection](#excluding-images-from-garbage-collection) 17 | * [Excluding Containers From Garbage Collection](#excluding-containers-from-garbage-collection) 18 | * [Running as a Docker Image](#running-as-a-docker-image) 19 | * [Build the Docker Image](#build-the-docker-image) 20 | * [Running as a Docker Container](#running-as-a-docker-container) 21 | 22 | A simple Docker container and image garbage collection script. 23 | 24 | * Containers that exited more than an hour ago are removed. 25 | * Images that don't belong to any remaining container after that are removed. 26 | * Optionally, remove volumes that are not associated to any remaining container after removal (Available only for docker >= 1.9.0) 27 | 28 | Although docker normally prevents removal of images that are in use by 29 | containers, we take extra care to not remove any image tags (e.g., ubuntu:14.04, 30 | busybox, etc) that are in use by containers. A naive `docker rmi $(docker images 31 | -q)` will leave images stripped of all tags, forcing docker to re-pull the 32 | repositories when starting new containers even though the images themselves are 33 | still on disk. 34 | 35 | This script is intended to be run as a cron job, but you can also run it as a Docker 36 | container (see [below](#running-as-a-docker-container)). 37 | 38 | ## Building the Debian Package 39 | 40 | 41 | ```sh 42 | sudo apt-get install git devscripts debhelper build-essential dh-make 43 | git clone https://github.com/spotify/docker-gc.git 44 | cd docker-gc 45 | debuild -us -uc -b 46 | ``` 47 | 48 | If you get lintian errors during `debuild`, try `debuild --no-lintian -us -uc -b`. 49 | 50 | 51 | ## Installing the Debian Package 52 | 53 | ```sh 54 | sudo dpkg -i ../docker-gc_0.1.0_all.deb 55 | ``` 56 | 57 | This installs the `docker-gc` script into `/usr/sbin`. If you want it to 58 | run as a cron job, you can configure it now by creating a root-owned 59 | executable file `/etc/cron.hourly/docker-gc` with the following contents: 60 | 61 | ``` 62 | #!/bin/bash 63 | /usr/sbin/docker-gc 64 | ``` 65 | 66 | To test that the job will actually run you can use this command 67 | 68 | ``` 69 | run-parts --test /etc/cron.hourly 70 | ``` 71 | 72 | ## Manual Usage 73 | 74 | To use the script manually, run `docker-gc`. The system user under 75 | which `docker-gc` runs needs to have read and write access to 76 | the `$STATE_DIR` environment variable which defaults to `/var/lib/docker-gc`. 77 | 78 | 79 | ### Excluding Images From Garbage Collection 80 | 81 | There can be images that are large that serve as a common base for 82 | many application containers, and as such, make sense to pin to the 83 | machine, as many derivative containers will use it. This can save 84 | time in pulling those kinds of images. There may be other reasons to 85 | exclude images from garbage collection. To do so, create 86 | `/etc/docker-gc-exclude`, or if you want the file to be read from 87 | elsewhere, set the `EXCLUDE_FROM_GC` environment variable to its 88 | location. This file can contain image name patterns (in the `grep` 89 | sense), one per line, such as `spotify/cassandra:latest` or it can 90 | contain image ids (truncated to the length shown in `docker images` 91 | which is 12. 92 | 93 | An example image excludes file might contain: 94 | ``` 95 | spotify/cassandra:latest 96 | redis:.* 97 | 9681260c3ad5 98 | ``` 99 | 100 | ### Excluding Containers From Garbage Collection 101 | 102 | There can also be containers (for example data only containers) which 103 | you would like to exclude from garbage collection. To do so, create 104 | `/etc/docker-gc-exclude-containers`, or if you want the file to be 105 | read from elsewhere, set the `EXCLUDE_CONTAINERS_FROM_GC` environment 106 | variable to its location. This file should contain name patterns (in 107 | the `grep` sense), one per line, such as `mariadb-data`. 108 | 109 | An example container excludes file might contain: 110 | ``` 111 | mariadb-data 112 | drunk_goodall 113 | ``` 114 | 115 | ### Excluding Volumes From Garbage Collection 116 | 117 | There can be occasions where you don't want to remove a dangling volume. 118 | To enable this functionality you can create a file named 119 | `/etc/docker-gc-exclude-volumes` (or specify `EXCLUDE_VOLUMES_IDS_FILE` env var 120 | with any path for such file), containing name patterns (in the `grep` sense), 121 | one per line, of volumes that will be excluded from garbage collection. 122 | 123 | ### Forcing deletion of images that have multiple tags 124 | 125 | By default, docker will not remove an image if it is tagged in multiple 126 | repositories. 127 | If you have a server running docker where this is the case, for example 128 | in CI environments where dockers are being built, re-tagged, and pushed, 129 | you can enable a force flag to override this default. 130 | 131 | ``` 132 | FORCE_IMAGE_REMOVAL=1 docker-gc 133 | ``` 134 | 135 | ### Preserving a minimum number of images for every repository 136 | 137 | You might want to always keep a set of the most recent images for any 138 | repository. For example, if you are continually rebuilding an image during 139 | development you would want to clear out all but the most recent version of an 140 | image. To do so, set the `MINIMUM_IMAGES_TO_SAVE=1` environment variable. You 141 | can preserve any count of the most recent images, e.g. save the most recent 10 142 | with `MINIMUM_IMAGES_TO_SAVE=10`. 143 | 144 | ### Forcing deletion of containers 145 | 146 | By default, if an error is encountered when cleaning up a container, Docker 147 | will report the error back and leave it on disk. This can sometimes lead to 148 | containers accumulating. If you run into this issue, you can force the removal 149 | of the container by setting the environment variable below: 150 | 151 | ``` 152 | FORCE_CONTAINER_REMOVAL=1 docker-gc 153 | ``` 154 | 155 | ### Excluding Recently Exited Containers and Images From Garbage Collection 156 | 157 | By default, docker-gc will not remove a container if it exited less than 3600 seconds (1 hour) ago. In some cases you might need to change this setting (e.g. you need exited containers to stick around for debugging for several days). Set the `GRACE_PERIOD_SECONDS` variable to override this default. 158 | 159 | ``` 160 | GRACE_PERIOD_SECONDS=86400 docker-gc 161 | ``` 162 | 163 | This setting also prevents the removal of images that have been created less than `GRACE_PERIOD_SECONDS` seconds ago. 164 | 165 | ### Dry run 166 | By default, docker-gc will proceed with deletion of containers and images. To test your command-line options set the `DRY_RUN` variable to override this default. 167 | 168 | ``` 169 | DRY_RUN=1 docker-gc 170 | ``` 171 | 172 | 173 | ## Running as a Docker Image 174 | 175 | A Dockerfile is provided as an alternative to a local installation. By default 176 | the container will start up, run a single garbage collection, and shut down. 177 | 178 | The image is published as `spotify/docker-gc`. 179 | 180 | #### Building the Docker Image 181 | The image is currently built with Docker 17.09.0-ce, but to build it against a newer 182 | Docker version (to ensure that the API version of the command-line interface 183 | matches with your Docker daemon), simply edit [the `ENV DOCKER_VERSION` line in 184 | `Dockerfile`][dockerfile-ENV] prior to the build step below. 185 | 186 | [dockerfile-ENV]: https://github.com/spotify/docker-gc/blob/fd6640fa8c133de53a0395a36e8dcbaf29842684/Dockerfile#L3 187 | 188 | Build the Docker image with `make -f Makefile.docker image` or: 189 | 190 | ```sh 191 | docker build -t spotify/docker-gc . 192 | ``` 193 | 194 | #### Running as a Docker Container 195 | 196 | The docker-gc container requires access to the docker socket in order to 197 | function, so you need to map it when running, e.g.: 198 | 199 | ```sh 200 | docker run --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc:ro spotify/docker-gc 201 | ``` 202 | 203 | The `/etc` directory is also mapped so that it can read any exclude files 204 | that you've created. 205 | 206 | If you want to remove volumes, you can do so by passing REMOVE_VOLUMES env var set to 1. 207 | 208 | ```sh 209 | $ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc -e REMOVE_VOLUMES=1 spotify/docker-gc 210 | ``` 211 | 212 | If you want to remove volumes only for a specified driver, you can do it by passing VOLUME_DELETE_ONLY_DRIVER env var set to the driver name. 213 | 214 | If your docker daemon is configured to run with user namespace, you will need to 215 | run the container with [user namespace disabled][disable-user-namespace]: 216 | 217 | ```sh 218 | docker run --rm --userns host -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc spotify/docker-gc 219 | ``` 220 | 221 | [disable-user-namespace]: https://docs.docker.com/engine/reference/commandline/dockerd/#disable-user-namespace-for-a-container 222 | [prune]: https://docs.docker.com/engine/reference/commandline/system_prune/ 223 | -------------------------------------------------------------------------------- /debian/.gitignore: -------------------------------------------------------------------------------- 1 | debhelper-build-stamp 2 | docker-gc.substvars 3 | docker-gc/ 4 | files 5 | 6 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | docker-gc (2:0.2.0) unstable; urgency=low 2 | 3 | * allow `docker inspect -f {{Created}}` to fail 4 | 5 | -- Matt Brown Mon, 05 Aug 2019 17:14:00 +0000 6 | 7 | docker-gc (2:0.1.0) unstable; urgency=low 8 | 9 | * Fixes: 10 | - Only remove images that are created at least GRACE_PERIOD_SECONDS ago 11 | - Do not exclude everything when excluding nothing 12 | - Should mount /etc as volumes when running as a docker container 13 | - Fix grep difference bug in excluding containers 14 | - handling a pid so that docker-gc will run only once at a time 15 | - Add support for excluding containers 16 | - Calculate elapsed time in Bash 17 | 18 | -- David Xia Mon, 05 Oct 2015 17:10:00 +0000 19 | 20 | docker-gc (0.0.4) unstable; urgency=low 21 | 22 | * Do not automatically install cron job 23 | 24 | -- Ryan Culbertson Mon, 06 Jul 2015 17:10:00 +0000 25 | 26 | docker-gc (0.0.3) unstable; urgency=low 27 | 28 | * Tolerate things not existing 29 | 30 | -- Drew Csillag Wed, 15 Oct 2014 20:20:20 +0000 31 | 32 | docker-gc (0.0.2) unstable; urgency=low 33 | 34 | * Allow for GC to ignore certain images 35 | 36 | -- Drew Csillag Tue, 14 Oct 2014 20:20:20 +0000 37 | 38 | docker-gc (0.0.1) unstable; urgency=low 39 | 40 | * Initial release. 41 | 42 | -- Daniel Norberg Sun, 22 Jun 2014 20:20:20 +0000 43 | -------------------------------------------------------------------------------- /debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: docker-gc 2 | Section: admin 3 | Priority: optional 4 | Maintainer: Daniel Norberg 5 | Build-Depends: debhelper (>= 9) 6 | Standards-Version: 3.9.5 7 | 8 | Package: docker-gc 9 | Architecture: all 10 | Depends: ${misc:Depends} 11 | Description: Docker garbage collection of containers and images. 12 | -------------------------------------------------------------------------------- /debian/dirs: -------------------------------------------------------------------------------- 1 | var/lib/docker-gc -------------------------------------------------------------------------------- /debian/install: -------------------------------------------------------------------------------- 1 | docker-gc usr/sbin/ 2 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | export DH_VERBOSE=1 4 | 5 | %: 6 | dh $@ 7 | -------------------------------------------------------------------------------- /docker-gc: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright (c) 2014 Spotify AB. 4 | # 5 | # Licensed to the Apache Software Foundation (ASF) under one 6 | # or more contributor license agreements. See the NOTICE file 7 | # distributed with this work for additional information 8 | # regarding copyright ownership. The ASF licenses this file 9 | # to you under the Apache License, Version 2.0 (the 10 | # "License"); you may not use this file except in compliance 11 | # with the License. You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, 16 | # software distributed under the License is distributed on an 17 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 18 | # KIND, either express or implied. See the License for the 19 | # specific language governing permissions and limitations 20 | # under the License. 21 | 22 | # This script attempts to garbage collect docker containers and images. 23 | # Containers that exited more than an hour ago are removed. 24 | # Images that have existed more than an hour and are not in use by any 25 | # containers are removed. 26 | 27 | # Note: Although docker normally prevents removal of images that are in use by 28 | # containers, we take extra care to not remove any image tags (e.g. 29 | # ubuntu:14.04, busybox, etc) that are used by containers. A naive 30 | # "docker rmi `docker images -q`" will leave images stripped of all tags, 31 | # forcing users to re-pull the repositories even though the images 32 | # themselves are still on disk. 33 | 34 | # Note: State is stored in $STATE_DIR, defaulting to /var/lib/docker-gc 35 | 36 | # The script can send log messages to syslog regarding which images and 37 | # containers were removed. To enable logging to syslog, set LOG_TO_SYSLOG=1. 38 | # When disabled, this script will instead log to standard out. When syslog is 39 | # enabled, the syslog facility and logger can be configured with 40 | # $SYSLOG_FACILITY and $SYSLOG_LEVEL respectively. 41 | 42 | set -o nounset 43 | set -o errexit 44 | 45 | GRACE_PERIOD_SECONDS=${GRACE_PERIOD_SECONDS:=3600} 46 | MINIMUM_IMAGES_TO_SAVE=${MINIMUM_IMAGES_TO_SAVE:=0} 47 | STATE_DIR=${STATE_DIR:=/var/lib/docker-gc} 48 | REMOVE_ASSOCIATED_VOLUME=${REMOVE_ASSOCIATED_VOLUME=1} 49 | FORCE_CONTAINER_REMOVAL=${FORCE_CONTAINER_REMOVAL:=0} 50 | FORCE_IMAGE_REMOVAL=${FORCE_IMAGE_REMOVAL:=0} 51 | DOCKER=${DOCKER:=docker} 52 | PID_DIR=${PID_DIR:=/var/run} 53 | LOG_TO_SYSLOG=${LOG_TO_SYSLOG:=0} 54 | SYSLOG_FACILITY=${SYSLOG_FACILITY:=user} 55 | SYSLOG_LEVEL=${SYSLOG_LEVEL:=info} 56 | SYSLOG_TAG=${SYSLOG_TAG:=docker-gc} 57 | DRY_RUN=${DRY_RUN:=0} 58 | EXCLUDE_DEAD=${EXCLUDE_DEAD:=0} 59 | REMOVE_VOLUMES=${REMOVE_VOLUMES:=0} 60 | EXCLUDE_VOLUMES_IDS_FILE=${EXCLUDE_VOLUMES_IDS_FILE:=/etc/docker-gc-exclude-volumes} 61 | VOLUME_DELETE_ONLY_DRIVER=${VOLUME_DELETE_ONLY_DRIVER:=local} 62 | PIDFILE=$PID_DIR/dockergc 63 | 64 | exec 3>>$PIDFILE 65 | if ! flock -x -n 3; then 66 | echo "[$(date)] : docker-gc : Process is already running" 67 | exit 1 68 | fi 69 | 70 | trap "rm -f -- '$PIDFILE'" EXIT 71 | 72 | echo $$ > $PIDFILE 73 | 74 | EXCLUDE_FROM_GC=${EXCLUDE_FROM_GC:=/etc/docker-gc-exclude} 75 | if [ ! -f "$EXCLUDE_FROM_GC" ]; then 76 | EXCLUDE_FROM_GC=/dev/null 77 | fi 78 | 79 | EXCLUDE_CONTAINERS_FROM_GC=${EXCLUDE_CONTAINERS_FROM_GC:=/etc/docker-gc-exclude-containers} 80 | if [ ! -f "$EXCLUDE_CONTAINERS_FROM_GC" ]; then 81 | EXCLUDE_CONTAINERS_FROM_GC=/dev/null 82 | fi 83 | 84 | EXCLUDE_IDS_FILE="exclude_ids" 85 | EXCLUDE_CONTAINER_IDS_FILE="exclude_container_ids" 86 | 87 | function date_parse() { 88 | if date --utc >/dev/null 2>&1; then 89 | # GNU/date 90 | date -u --date "${1}" "+%s" 91 | else 92 | # BSD/date 93 | date -j -u -f "%F %T" "${1}" "+%s" 94 | fi 95 | } 96 | 97 | # Elapsed time since a docker timestamp, in seconds 98 | function elapsed_time() { 99 | # Docker 1.5.0 datetime format is 2015-07-03T02:39:00.390284991 100 | # Docker 1.7.0 datetime format is 2015-07-03 02:39:00.390284991 +0000 UTC 101 | utcnow=$(date -u "+%s") 102 | replace_q="${1#\"}" 103 | without_ms="${replace_q:0:19}" 104 | replace_t="${without_ms/T/ }" 105 | epoch=$(date_parse "${replace_t}") 106 | echo $(($utcnow - $epoch)) 107 | } 108 | 109 | function compute_exclude_ids() { 110 | # Find images that match patterns in the EXCLUDE_FROM_GC file and put their 111 | # id prefixes into $EXCLUDE_IDS_FILE, prefixed with ^ 112 | 113 | PROCESSED_EXCLUDES="processed_excludes.tmp" 114 | # Take each line and put a space at the beginning and end, so when we 115 | # grep for them below, it will effectively be: "match either repo:tag 116 | # or imageid". Also delete blank lines or lines that only contain 117 | # whitespace 118 | sed 's/^\(.*\)$/ \1 /' $EXCLUDE_FROM_GC | sed '/^ *$/d' > $PROCESSED_EXCLUDES 119 | # The following looks a bit of a mess, but here's what it does: 120 | # 1. Get images 121 | # 2. Skip header line 122 | # 3. Turn columnar display of 'REPO TAG IMAGEID ....' to 'REPO:TAG IMAGEID' 123 | # 4. find lines that contain things mentioned in PROCESSED_EXCLUDES 124 | # 5. Grab the image id from the line 125 | # 6. Prepend ^ to the beginning of each line 126 | 127 | # What this does is make grep patterns to match image ids mentioned by 128 | # either repo:tag or image id for later greppage 129 | $DOCKER images \ 130 | | tail -n+2 \ 131 | | sed 's/^\([^ ]*\) *\([^ ]*\) *\([^ ]*\).*/ \1:\2 \3 /' \ 132 | | grep -f $PROCESSED_EXCLUDES 2>/dev/null \ 133 | | cut -d' ' -f3 \ 134 | | sed 's/^/^(sha256:)?/' > $EXCLUDE_IDS_FILE 135 | } 136 | 137 | function compute_exclude_container_ids() { 138 | # Find containers matching to patterns listed in EXCLUDE_CONTAINERS_FROM_GC file 139 | # Implode their values with a \| separator on a single line 140 | PROCESSED_EXCLUDES=`xargs < $EXCLUDE_CONTAINERS_FROM_GC \ 141 | | sed -e 's/ /\|/g'` 142 | # The empty string would match everything 143 | if [ "$PROCESSED_EXCLUDES" = "" ]; then 144 | touch $EXCLUDE_CONTAINER_IDS_FILE 145 | return 146 | fi 147 | # Find all docker images 148 | # Filter out with matching names 149 | # and put them to $EXCLUDE_CONTAINER_IDS_FILE 150 | $DOCKER ps -a \ 151 | | grep -E "$PROCESSED_EXCLUDES" \ 152 | | awk '{ print $1 }' \ 153 | | tr -s " " "\012" \ 154 | | sort -u > $EXCLUDE_CONTAINER_IDS_FILE 155 | } 156 | 157 | function log() { 158 | msg=$1 159 | if [[ $LOG_TO_SYSLOG -gt 0 ]]; then 160 | logger -i -t "$SYSLOG_TAG" -p "$SYSLOG_FACILITY.$SYSLOG_LEVEL" "$msg" 161 | else 162 | echo "[$(date +'%Y-%m-%dT%H:%M:%S')] [INFO] : $msg" 163 | fi 164 | } 165 | 166 | function container_log() { 167 | prefix=$1 168 | filename=$2 169 | 170 | while IFS='' read -r containerid 171 | do 172 | log "$prefix $containerid $(${DOCKER} inspect -f {{.Name}} $containerid)" 173 | done < "$filename" 174 | } 175 | 176 | function image_log() { 177 | prefix=$1 178 | filename=$2 179 | 180 | while IFS='' read -r imageid 181 | do 182 | log "$prefix $imageid $(${DOCKER} inspect -f {{.RepoTags}} $imageid)" 183 | done < "$filename" 184 | } 185 | 186 | function volumes_log() { 187 | prefix=$1 188 | filename=$2 189 | 190 | while IFS='' read -r volumeid 191 | do 192 | log "$prefix $volumeid" 193 | done < "$filename" 194 | } 195 | 196 | # Change into the state directory (and create it if it doesn't exist) 197 | if [ ! -d "$STATE_DIR" ]; then 198 | mkdir -p $STATE_DIR 199 | fi 200 | cd "$STATE_DIR" 201 | 202 | # Verify that docker is reachable 203 | $DOCKER version 1>/dev/null 204 | 205 | # List all currently existing containers 206 | $DOCKER ps -a -q --no-trunc | sort | uniq > containers.all 207 | 208 | # List running containers 209 | $DOCKER ps -q --no-trunc | sort | uniq > containers.running 210 | container_log "Container running" containers.running 211 | 212 | # compute ids of container images to exclude from GC 213 | compute_exclude_ids 214 | 215 | # compute ids of containers to exclude from GC 216 | compute_exclude_container_ids 217 | 218 | # List containers that are not running 219 | comm -23 containers.all containers.running > containers.exited 220 | 221 | if [[ $EXCLUDE_DEAD -gt 0 ]]; then 222 | echo "Excluding dead containers" 223 | # List dead containers 224 | $DOCKER ps -q -a -f status=dead | sort | uniq > containers.dead 225 | comm -23 containers.exited containers.dead > containers.exited.tmp 226 | cp containers.exited.tmp containers.exited 227 | fi 228 | 229 | container_log "Container not running" containers.exited 230 | 231 | # Find exited containers that finished at least GRACE_PERIOD_SECONDS ago 232 | > containers.reap.tmp 233 | while read line 234 | do 235 | EXITED=$(${DOCKER} inspect -f "{{json .State.FinishedAt}}" ${line}) 236 | ELAPSED=$(elapsed_time $EXITED) 237 | if [[ $ELAPSED -gt $GRACE_PERIOD_SECONDS ]]; then 238 | echo $line >> containers.reap.tmp 239 | fi 240 | done < containers.exited 241 | 242 | # List containers that we will remove and exclude ids. 243 | sort containers.reap.tmp | uniq | grep -v -f $EXCLUDE_CONTAINER_IDS_FILE > containers.reap || true 244 | 245 | # List containers that we will keep. 246 | comm -23 containers.all containers.reap > containers.keep 247 | 248 | # List images used by containers that we keep. 249 | xargs -n 1 $DOCKER inspect -f '{{.Image}}' < containers.keep 2>/dev/null | 250 | sort | uniq > images.used 251 | 252 | # List images to reap; images that existed last run and are not in use. 253 | echo -n "" > images.all 254 | $DOCKER images | while read line 255 | do 256 | awk '{print $1};' 257 | done | sort | uniq | while read line 258 | do 259 | $DOCKER images --no-trunc --format "{{.ID}} {{.CreatedAt}}" $line \ 260 | | sort -k 2 -r \ 261 | | tail -n +$((MINIMUM_IMAGES_TO_SAVE+1)) \ 262 | | cut -f 1 -d " " \ 263 | | uniq >> images.all 264 | done 265 | 266 | # Add dangling images to list. 267 | $DOCKER images --no-trunc --format "{{.ID}}" --filter dangling=true >> images.all 268 | 269 | # Find images that are created at least GRACE_PERIOD_SECONDS ago 270 | > images.reap.tmp 271 | sort images.all | uniq | while read line 272 | do 273 | # the `docker inspect` command might fail sometimes due to issues like 274 | # https://github.com/moby/moby/issues/35747 - don't let that abort this script 275 | set +o errexit 276 | CREATED=$(${DOCKER} inspect -f "{{.Created}}" ${line}) 277 | retval=$? 278 | set -o errexit 279 | if [ $retval -eq 0 ]; then 280 | ELAPSED=$(elapsed_time $CREATED) 281 | if [[ $ELAPSED -gt $GRACE_PERIOD_SECONDS ]]; then 282 | echo $line >> images.reap.tmp 283 | fi 284 | fi 285 | done 286 | comm -23 images.reap.tmp images.used | grep -E -v -f $EXCLUDE_IDS_FILE > images.reap || true 287 | 288 | # Use -f flag on docker rm command; forces removal of images that are in Dead 289 | # status or give errors when removing. 290 | FORCE_CONTAINER_FLAG="" 291 | if [[ $FORCE_CONTAINER_REMOVAL -gt 0 ]]; then 292 | FORCE_CONTAINER_FLAG="-f" 293 | fi 294 | 295 | # Remove associated volume, so that we won't create new orphan volumes. 296 | if [[ $REMOVE_ASSOCIATED_VOLUME -gt 0 ]]; then 297 | if [[ -z $FORCE_CONTAINER_FLAG ]]; then 298 | FORCE_CONTAINER_FLAG="-v" 299 | else 300 | FORCE_CONTAINER_FLAG=$FORCE_CONTAINER_FLAG"v" 301 | fi 302 | fi 303 | # Reap containers. 304 | if [[ $DRY_RUN -gt 0 ]]; then 305 | container_log "The following container would have been removed" containers.reap 306 | else 307 | container_log "Removing containers" containers.reap 308 | xargs -n 1 $DOCKER rm $FORCE_CONTAINER_FLAG --volumes=true < containers.reap &>/dev/null || true 309 | fi 310 | 311 | # Use -f flag on docker rmi command; forces removal of images that have multiple tags 312 | FORCE_IMAGE_FLAG="" 313 | if [[ $FORCE_IMAGE_REMOVAL -gt 0 ]]; then 314 | FORCE_IMAGE_FLAG="-f" 315 | fi 316 | 317 | # Reap images. 318 | if [[ $DRY_RUN -gt 0 ]]; then 319 | image_log "The following image would have been removed" images.reap 320 | else 321 | image_log "Removing image" images.reap 322 | xargs -n 1 $DOCKER rmi $FORCE_IMAGE_FLAG < images.reap &>/dev/null || true 323 | fi 324 | 325 | if [[ $REMOVE_VOLUMES -gt 0 ]]; then 326 | set +e 327 | $DOCKER volume ls --filter "dangling=true" -q &> /dev/null 328 | VOLUMES=$? 329 | set -e 330 | # If docker volume ls fails, then is probably not supported by either client or server 331 | if [ ! -f "$EXCLUDE_VOLUMES_IDS_FILE" ]; then 332 | EXCLUDE_VOLUMES_IDS_FILE=/dev/null 333 | fi 334 | 335 | if [[ $VOLUMES -gt 0 ]]; then 336 | set +e 337 | VERSION=$($DOCKER version --format="Client: {{.Client.Version}} Server: {{.Server.Version}}" 2&>/dev/null) 338 | FORMAT=$? 339 | set -e 340 | if [[ $FORMAT -gt 0 ]]; then 341 | log "Removing volumes is not supported for Docker < 1.9.0" 342 | else 343 | MESSAGE="Removing volumes is not supported for for docker version "$($DOCKER version --format="Client: {{.Client.Version}} Server: {{.Server.Version}}") & 344 | log "$MESSAGE" 345 | fi 346 | else 347 | if [[ -z "$VOLUME_DELETE_ONLY_DRIVER" ]]; then 348 | $DOCKER volume ls --filter "dangling=true" -q | grep -v -f $EXCLUDE_VOLUMES_IDS_FILE > volumes.reap || true 349 | else 350 | $DOCKER volume ls --filter "dangling=true" --filter "driver=$VOLUME_DELETE_ONLY_DRIVER" -q | grep -v -f $EXCLUDE_VOLUMES_IDS_FILE > volumes.reap || true 351 | fi 352 | 353 | if [[ $DRY_RUN -gt 0 ]]; then 354 | volumes_log "The following volume would have been removed" volumes.reap 355 | else 356 | volumes_log "Removing volume" volumes.reap 357 | xargs -n 1 $DOCKER volume rm < volumes.reap &>/dev/null || true 358 | fi 359 | fi 360 | fi 361 | -------------------------------------------------------------------------------- /rpm/.gitignore: -------------------------------------------------------------------------------- 1 | BUILD/ 2 | BUILDROOT/ 3 | RPMS/ 4 | SPECS/ 5 | SRPMS/ 6 | -------------------------------------------------------------------------------- /rpm/Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: rpm 3 | 4 | rpm: 5 | mkdir -p BUILDROOT/ 6 | rpmbuild \ 7 | --define "version `< ../version.txt`" \ 8 | --define "_topdir `pwd`" \ 9 | --define "_sourcedir %{_topdir}/.." \ 10 | -ba ./docker-gc.spec 11 | 12 | clean: 13 | rm -rfv BUILD BUILDROOT SPECS SRPMS RPMS 14 | -------------------------------------------------------------------------------- /rpm/docker-gc.spec: -------------------------------------------------------------------------------- 1 | Name: docker-gc 2 | Version: %{version} 3 | Release: 1%{?dist} 4 | Summary: Docker garbage collection of containers and images. 5 | BuildArch: noarch 6 | 7 | License: Apache 8 | 9 | %description 10 | Docker garbage collection of containers and images. 11 | 12 | %install 13 | mkdir -p $RPM_BUILD_ROOT/usr/sbin 14 | install -m 775 $RPM_SOURCE_DIR/docker-gc $RPM_BUILD_ROOT/usr/sbin/docker-gc 15 | 16 | %files 17 | /usr/sbin/docker-gc 18 | -------------------------------------------------------------------------------- /tests/run-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for i in $(dirname $0)/test-*.sh; do 4 | echo "Running ${i}..." 5 | ${i} 6 | done 7 | -------------------------------------------------------------------------------- /tests/test-volume-removal.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Regression test for https://github.com/spotify/docker-gc/issues/201 4 | 5 | set -euxo pipefail 6 | 7 | # when no volume exists then docker-gc should exit with status 0 8 | REMOVE_VOLUMES=1 ./docker-gc 9 | 10 | # when a volume exists it should be removed 11 | docker volume create 12 | if [[ $(docker volume ls --format "{{.Name}}" | wc -l) != 1 ]]; then echo "Volume count is not 1" && exit 1; fi 13 | REMOVE_VOLUMES=1 ./docker-gc 14 | if [[ $(docker volume ls --format "{{.Name}}" | wc -l) != 0 ]]; then echo "Volume has not been removed" && exit 1; fi 15 | -------------------------------------------------------------------------------- /version.txt: -------------------------------------------------------------------------------- 1 | 0.2.1 2 | --------------------------------------------------------------------------------