├── debian ├── compat ├── dirs ├── install ├── rules ├── .gitignore ├── control └── changelog ├── version.txt ├── .dockerignore ├── rpm ├── .gitignore ├── Makefile └── docker-gc.spec ├── .travis.yml ├── Makefile.docker ├── .github ├── stale.yml └── ISSUE_TEMPLATE.md ├── Dockerfile ├── CONTRIBUTING.md ├── README.md ├── LICENSE └── docker-gc /debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /version.txt: -------------------------------------------------------------------------------- 1 | 0.2.1 2 | -------------------------------------------------------------------------------- /debian/dirs: -------------------------------------------------------------------------------- 1 | var/lib/docker-gc -------------------------------------------------------------------------------- /debian/install: -------------------------------------------------------------------------------- 1 | docker-gc usr/sbin/ 2 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .git/ 2 | debian/ 3 | 4 | -------------------------------------------------------------------------------- /rpm/.gitignore: -------------------------------------------------------------------------------- 1 | BUILD/ 2 | BUILDROOT/ 3 | RPMS/ 4 | SPECS/ 5 | SRPMS/ 6 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | export DH_VERBOSE=1 4 | 5 | %: 6 | dh $@ 7 | -------------------------------------------------------------------------------- /debian/.gitignore: -------------------------------------------------------------------------------- 1 | debhelper-build-stamp 2 | docker-gc.substvars 3 | docker-gc/ 4 | files 5 | 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | services: 4 | - docker 5 | 6 | script: 7 | - DOCKER_TAG=travisci make -f Makefile.docker image 8 | # make sure image can run 9 | - docker run -e LOG_TO_SYSLOG=0 -v /var/run/docker.sock:/var/run/docker.sock spotify/docker-gc:travisci 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gliderlabs/alpine:3.2 2 | 3 | ENV DOCKER_VERSION 17.09.0-ce 4 | 5 | # We get curl so that we can avoid a separate ADD to fetch the Docker binary, and then we'll remove it 6 | RUN apk --update add bash curl \ 7 | && cd /tmp/ \ 8 | && curl -sSL -O https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz \ 9 | && tar zxf docker-${DOCKER_VERSION}.tgz \ 10 | && mkdir -p /usr/local/bin/ \ 11 | && mv $(find -name 'docker' -type f) /usr/local/bin/ \ 12 | && chmod +x /usr/local/bin/docker \ 13 | && apk del curl \ 14 | && rm -rf /tmp/* \ 15 | && rm -rf /var/cache/apk/* 16 | 17 | COPY ./docker-gc /docker-gc 18 | 19 | VOLUME /var/lib/docker-gc 20 | 21 | CMD ["/docker-gc"] 22 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | docker-gc (2:0.1.0) unstable; urgency=low 2 | 3 | * Fixes: 4 | - Only remove images that are created at least GRACE_PERIOD_SECONDS ago 5 | - Do not exclude everything when excluding nothing 6 | - Should mount /etc as volumes when running as a docker container 7 | - Fix grep difference bug in excluding containers 8 | - handling a pid so that docker-gc will run only once at a time 9 | - Add support for excluding containers 10 | - Calculate elapsed time in Bash 11 | 12 | -- David Xia Mon, 05 Oct 2015 17:10:00 +0000 13 | 14 | docker-gc (0.0.4) unstable; urgency=low 15 | 16 | * Do not automatically install cron job 17 | 18 | -- Ryan Culbertson Mon, 06 Jul 2015 17:10:00 +0000 19 | 20 | docker-gc (0.0.3) unstable; urgency=low 21 | 22 | * Tolerate things not existing 23 | 24 | -- Drew Csillag Wed, 15 Oct 2014 20:20:20 +0000 25 | 26 | docker-gc (0.0.2) unstable; urgency=low 27 | 28 | * Allow for GC to ignore certain images 29 | 30 | -- Drew Csillag Tue, 14 Oct 2014 20:20:20 +0000 31 | 32 | docker-gc (0.0.1) unstable; urgency=low 33 | 34 | * Initial release. 35 | 36 | -- Daniel Norberg Sun, 22 Jun 2014 20:20:20 +0000 37 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # docker-gc 2 | 3 | * [Building](#building) 4 | * [Installing](#installing) 5 | * [Usage](#usage) 6 | * [Excluding Images From Garbage Collection](#excluding-images-from-garbage-collection) 7 | * [Excluding Containers From Garbage Collection](#excluding-containers-from-garbage-collection) 8 | * [Running as a Docker Image](#running-as-a-docker-image) 9 | * [Build the Docker Image](#build-the-docker-image) 10 | * [Running as a Docker Container](#running-as-a-docker-container) 11 | 12 | A simple Docker container and image garbage collection script. 13 | 14 | * Containers that exited more than an hour ago are removed. 15 | * Images that don't belong to any remaining container after that are removed. 16 | * Optionally, remove volumes that are not associated to any remaining container after removal (Available only for docker >= 1.9.0) 17 | 18 | Although docker normally prevents removal of images that are in use by 19 | containers, we take extra care to not remove any image tags (e.g., ubuntu:14.04, 20 | busybox, etc) that are in use by containers. A naive `docker rmi $(docker images 21 | -q)` will leave images stripped of all tags, forcing docker to re-pull the 22 | repositories when starting new containers even though the images themselves are 23 | still on disk. 24 | 25 | This script is intended to be run as a cron job, but you can also run it as a Docker 26 | container (see [below](#running-as-a-docker-container)). 27 | 28 | ## Building the Debian Package 29 | 30 | 31 | ```sh 32 | sudo apt-get install git devscripts debhelper build-essential dh-make 33 | git clone https://github.com/spotify/docker-gc.git 34 | cd docker-gc 35 | debuild -us -uc -b 36 | ``` 37 | 38 | If you get lintian errors during `debuild`, try `debuild --no-lintian -us -uc -b`. 39 | 40 | 41 | ## Installing the Debian Package 42 | 43 | ```sh 44 | sudo dpkg -i ../docker-gc_0.1.0_all.deb 45 | ``` 46 | 47 | This installs the `docker-gc` script into `/usr/sbin`. If you want it to 48 | run as a cron job, you can configure it now by creating a root-owned 49 | executable file `/etc/cron.hourly/docker-gc` with the following contents: 50 | 51 | ``` 52 | #!/bin/bash 53 | /usr/sbin/docker-gc 54 | ``` 55 | 56 | To test that the job will actually run you can use this command 57 | 58 | ``` 59 | run-parts --test /etc/cron.hourly 60 | ``` 61 | 62 | ## Manual Usage 63 | 64 | To use the script manually, run `docker-gc`. The system user under 65 | which `docker-gc` runs needs to have read and write access to 66 | the `$STATE_DIR` environment variable which defaults to `/var/lib/docker-gc`. 67 | 68 | 69 | ### Excluding Images From Garbage Collection 70 | 71 | There can be images that are large that serve as a common base for 72 | many application containers, and as such, make sense to pin to the 73 | machine, as many derivative containers will use it. This can save 74 | time in pulling those kinds of images. There may be other reasons to 75 | exclude images from garbage collection. To do so, create 76 | `/etc/docker-gc-exclude`, or if you want the file to be read from 77 | elsewhere, set the `EXCLUDE_FROM_GC` environment variable to its 78 | location. This file can contain image name patterns (in the `grep` 79 | sense), one per line, such as `spotify/cassandra:latest` or it can 80 | contain image ids (truncated to the length shown in `docker images` 81 | which is 12. 82 | 83 | An example image excludes file might contain: 84 | ``` 85 | spotify/cassandra:latest 86 | redis:.* 87 | 9681260c3ad5 88 | ``` 89 | 90 | ### Excluding Containers From Garbage Collection 91 | 92 | There can also be containers (for example data only containers) which 93 | you would like to exclude from garbage collection. To do so, create 94 | `/etc/docker-gc-exclude-containers`, or if you want the file to be 95 | read from elsewhere, set the `EXCLUDE_CONTAINERS_FROM_GC` environment 96 | variable to its location. This file should contain name patterns (in 97 | the `grep` sense), one per line, such as `mariadb-data`. 98 | 99 | An example container excludes file might contain: 100 | ``` 101 | mariadb-data 102 | drunk_goodall 103 | ``` 104 | 105 | ### Excluding Volumes From Garbage Collection 106 | 107 | There can be occasions where you don't want to remove a dangling volume. 108 | To enable this functionality you can create a file named 109 | `/etc/docker-gc-exclude-volumes` (or specify `EXCLUDE_VOLUMES_IDS_FILE` env var 110 | with any path for such file), containing name patterns (in the `grep` sense), 111 | one per line, of volumes that will be excluded from garbage collection. 112 | 113 | ### Forcing deletion of images that have multiple tags 114 | 115 | By default, docker will not remove an image if it is tagged in multiple 116 | repositories. 117 | If you have a server running docker where this is the case, for example 118 | in CI environments where dockers are being built, re-tagged, and pushed, 119 | you can enable a force flag to override this default. 120 | 121 | ``` 122 | FORCE_IMAGE_REMOVAL=1 docker-gc 123 | ``` 124 | 125 | ### Preserving a minimum number of images for every repository 126 | 127 | You might want to always keep a set of the most recent images for any 128 | repository. For example, if you are continually rebuilding an image during 129 | development you would want to clear out all but the most recent version of an 130 | image. To do so, set the `MINIMUM_IMAGES_TO_SAVE=1` environment variable. You 131 | can preserve any count of the most recent images, e.g. save the most recent 10 132 | with `MINIMUM_IMAGES_TO_SAVE=10`. 133 | 134 | ### Forcing deletion of containers 135 | 136 | By default, if an error is encountered when cleaning up a container, Docker 137 | will report the error back and leave it on disk. This can sometimes lead to 138 | containers accumulating. If you run into this issue, you can force the removal 139 | of the container by setting the environment variable below: 140 | 141 | ``` 142 | FORCE_CONTAINER_REMOVAL=1 docker-gc 143 | ``` 144 | 145 | ### Excluding Recently Exited Containers and Images From Garbage Collection 146 | 147 | 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. 148 | 149 | ``` 150 | GRACE_PERIOD_SECONDS=86400 docker-gc 151 | ``` 152 | 153 | This setting also prevents the removal of images that have been created less than `GRACE_PERIOD_SECONDS` seconds ago. 154 | 155 | ### Dry run 156 | 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. 157 | 158 | ``` 159 | DRY_RUN=1 docker-gc 160 | ``` 161 | 162 | 163 | ## Running as a Docker Image 164 | 165 | A Dockerfile is provided as an alternative to a local installation. By default 166 | the container will start up, run a single garbage collection, and shut down. 167 | 168 | The image is published as `spotify/docker-gc`. 169 | 170 | #### Building the Docker Image 171 | The image is currently built with Docker 17.09.0-ce, but to build it against a newer 172 | Docker version (to ensure that the API version of the command-line interface 173 | matches with your Docker daemon), simply edit [the `ENV DOCKER_VERSION` line in 174 | `Dockerfile`][dockerfile-ENV] prior to the build step below. 175 | 176 | [dockerfile-ENV]: https://github.com/spotify/docker-gc/blob/fd6640fa8c133de53a0395a36e8dcbaf29842684/Dockerfile#L3 177 | 178 | Build the Docker image with `make -f Makefile.docker image` or: 179 | 180 | ```sh 181 | docker build -t spotify/docker-gc . 182 | ``` 183 | 184 | #### Running as a Docker Container 185 | 186 | The docker-gc container requires access to the docker socket in order to 187 | function, so you need to map it when running, e.g.: 188 | 189 | ```sh 190 | docker run --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc:ro spotify/docker-gc 191 | ``` 192 | 193 | The `/etc` directory is also mapped so that it can read any exclude files 194 | that you've created. 195 | 196 | If you want to remove volumes, you can do so by passing REMOVE_VOLUMES env var set to 1. 197 | 198 | ```sh 199 | $ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc -e REMOVE_VOLUMES=1 spotify/docker-gc 200 | ``` 201 | 202 | 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. 203 | 204 | If your docker daemon is configured to run with user namespace, you will need to 205 | run the container with [user namespace disabled][disable-user-namespace]: 206 | 207 | ```sh 208 | docker run --rm --userns host -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc spotify/docker-gc 209 | ``` 210 | 211 | [disable-user-namespace]: https://docs.docker.com/engine/reference/commandline/dockerd/#disable-user-namespace-for-a-container 212 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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" ] 76 | then 77 | EXCLUDE_FROM_GC=/dev/null 78 | fi 79 | 80 | EXCLUDE_CONTAINERS_FROM_GC=${EXCLUDE_CONTAINERS_FROM_GC:=/etc/docker-gc-exclude-containers} 81 | if [ ! -f "$EXCLUDE_CONTAINERS_FROM_GC" ] 82 | then 83 | EXCLUDE_CONTAINERS_FROM_GC=/dev/null 84 | fi 85 | 86 | EXCLUDE_IDS_FILE="exclude_ids" 87 | EXCLUDE_CONTAINER_IDS_FILE="exclude_container_ids" 88 | 89 | function date_parse { 90 | if date --utc >/dev/null 2>&1; then 91 | # GNU/date 92 | echo $(date -u --date "${1}" "+%s") 93 | else 94 | # BSD/date 95 | echo $(date -j -u -f "%F %T" "${1}" "+%s") 96 | fi 97 | } 98 | 99 | # Elapsed time since a docker timestamp, in seconds 100 | function elapsed_time() { 101 | # Docker 1.5.0 datetime format is 2015-07-03T02:39:00.390284991 102 | # Docker 1.7.0 datetime format is 2015-07-03 02:39:00.390284991 +0000 UTC 103 | utcnow=$(date -u "+%s") 104 | replace_q="${1#\"}" 105 | without_ms="${replace_q:0:19}" 106 | replace_t="${without_ms/T/ }" 107 | epoch=$(date_parse "${replace_t}") 108 | echo $(($utcnow - $epoch)) 109 | } 110 | 111 | function compute_exclude_ids() { 112 | # Find images that match patterns in the EXCLUDE_FROM_GC file and put their 113 | # id prefixes into $EXCLUDE_IDS_FILE, prefixed with ^ 114 | 115 | PROCESSED_EXCLUDES="processed_excludes.tmp" 116 | # Take each line and put a space at the beginning and end, so when we 117 | # grep for them below, it will effectively be: "match either repo:tag 118 | # or imageid". Also delete blank lines or lines that only contain 119 | # whitespace 120 | sed 's/^\(.*\)$/ \1 /' $EXCLUDE_FROM_GC | sed '/^ *$/d' > $PROCESSED_EXCLUDES 121 | # The following looks a bit of a mess, but here's what it does: 122 | # 1. Get images 123 | # 2. Skip header line 124 | # 3. Turn columnar display of 'REPO TAG IMAGEID ....' to 'REPO:TAG IMAGEID' 125 | # 4. find lines that contain things mentioned in PROCESSED_EXCLUDES 126 | # 5. Grab the image id from the line 127 | # 6. Prepend ^ to the beginning of each line 128 | 129 | # What this does is make grep patterns to match image ids mentioned by 130 | # either repo:tag or image id for later greppage 131 | $DOCKER images \ 132 | | tail -n+2 \ 133 | | sed 's/^\([^ ]*\) *\([^ ]*\) *\([^ ]*\).*/ \1:\2 \3 /' \ 134 | | grep -f $PROCESSED_EXCLUDES 2>/dev/null \ 135 | | cut -d' ' -f3 \ 136 | | sed 's/^/^(sha256:)?/' > $EXCLUDE_IDS_FILE 137 | } 138 | 139 | function compute_exclude_container_ids() { 140 | # Find containers matching to patterns listed in EXCLUDE_CONTAINERS_FROM_GC file 141 | # Implode their values with a \| separator on a single line 142 | PROCESSED_EXCLUDES=`cat $EXCLUDE_CONTAINERS_FROM_GC \ 143 | | xargs \ 144 | | sed -e 's/ /\|/g'` 145 | # The empty string would match everything 146 | if [ "$PROCESSED_EXCLUDES" = "" ]; then 147 | touch $EXCLUDE_CONTAINER_IDS_FILE 148 | return 149 | fi 150 | # Find all docker images 151 | # Filter out with matching names 152 | # and put them to $EXCLUDE_CONTAINER_IDS_FILE 153 | $DOCKER ps -a \ 154 | | grep -E "$PROCESSED_EXCLUDES" \ 155 | | awk '{ print $1 }' \ 156 | | tr -s " " "\012" \ 157 | | sort -u > $EXCLUDE_CONTAINER_IDS_FILE 158 | } 159 | 160 | function log() { 161 | msg=$1 162 | if [[ $LOG_TO_SYSLOG -gt 0 ]]; then 163 | logger -i -t "$SYSLOG_TAG" -p "$SYSLOG_FACILITY.$SYSLOG_LEVEL" "$msg" 164 | else 165 | echo "[$(date +'%Y-%m-%dT%H:%M:%S')] [INFO] : $msg" 166 | fi 167 | } 168 | 169 | function container_log() { 170 | prefix=$1 171 | filename=$2 172 | 173 | while IFS='' read -r containerid 174 | do 175 | log "$prefix $containerid $(${DOCKER} inspect -f {{.Name}} $containerid)" 176 | done < "$filename" 177 | } 178 | 179 | function image_log() { 180 | prefix=$1 181 | filename=$2 182 | 183 | while IFS='' read -r imageid 184 | do 185 | log "$prefix $imageid $(${DOCKER} inspect -f {{.RepoTags}} $imageid)" 186 | done < "$filename" 187 | } 188 | 189 | function volumes_log() { 190 | prefix=$1 191 | filename=$2 192 | 193 | while IFS='' read -r volumeid 194 | do 195 | log "$prefix $volumeid" 196 | done < "$filename" 197 | } 198 | 199 | # Change into the state directory (and create it if it doesn't exist) 200 | if [ ! -d "$STATE_DIR" ] 201 | then 202 | mkdir -p $STATE_DIR 203 | fi 204 | cd "$STATE_DIR" 205 | 206 | # Verify that docker is reachable 207 | $DOCKER version 1>/dev/null 208 | 209 | # List all currently existing containers 210 | $DOCKER ps -a -q --no-trunc | sort | uniq > containers.all 211 | 212 | # List running containers 213 | $DOCKER ps -q --no-trunc | sort | uniq > containers.running 214 | container_log "Container running" containers.running 215 | 216 | # compute ids of container images to exclude from GC 217 | compute_exclude_ids 218 | 219 | # compute ids of containers to exclude from GC 220 | compute_exclude_container_ids 221 | 222 | # List containers that are not running 223 | comm -23 containers.all containers.running > containers.exited 224 | 225 | if [[ $EXCLUDE_DEAD -gt 0 ]]; then 226 | echo "Excluding dead containers" 227 | # List dead containers 228 | $DOCKER ps -q -a -f status=dead | sort | uniq > containers.dead 229 | comm -23 containers.exited containers.dead > containers.exited.tmp 230 | cat containers.exited.tmp > containers.exited 231 | fi 232 | 233 | container_log "Container not running" containers.exited 234 | 235 | # Find exited containers that finished at least GRACE_PERIOD_SECONDS ago 236 | > containers.reap.tmp 237 | cat containers.exited | while read line 238 | do 239 | EXITED=$(${DOCKER} inspect -f "{{json .State.FinishedAt}}" ${line}) 240 | ELAPSED=$(elapsed_time $EXITED) 241 | if [[ $ELAPSED -gt $GRACE_PERIOD_SECONDS ]]; then 242 | echo $line >> containers.reap.tmp 243 | fi 244 | done 245 | 246 | # List containers that we will remove and exclude ids. 247 | cat containers.reap.tmp | sort | uniq | grep -v -f $EXCLUDE_CONTAINER_IDS_FILE > containers.reap || true 248 | 249 | # List containers that we will keep. 250 | comm -23 containers.all containers.reap > containers.keep 251 | 252 | # List images used by containers that we keep. 253 | cat containers.keep | 254 | xargs -n 1 $DOCKER inspect -f '{{.Image}}' 2>/dev/null | 255 | sort | uniq > images.used 256 | 257 | # List images to reap; images that existed last run and are not in use. 258 | echo -n "" > images.all 259 | $DOCKER images | while read line 260 | do 261 | awk '{print $1};' 262 | done | sort | uniq | while read line 263 | do 264 | $DOCKER images --no-trunc --format "{{.ID}} {{.CreatedAt}}" $line \ 265 | | sort -k 2 -r \ 266 | | tail -n +$((MINIMUM_IMAGES_TO_SAVE+1)) \ 267 | | cut -f 1 -d " " \ 268 | | uniq >> images.all 269 | done 270 | 271 | # Add dangling images to list. 272 | $DOCKER images --no-trunc --format "{{.ID}}" --filter dangling=true >> images.all 273 | 274 | # Find images that are created at least GRACE_PERIOD_SECONDS ago 275 | > images.reap.tmp 276 | cat images.all | sort | uniq | while read line 277 | do 278 | CREATED=$(${DOCKER} inspect -f "{{.Created}}" ${line}) 279 | ELAPSED=$(elapsed_time $CREATED) 280 | if [[ $ELAPSED -gt $GRACE_PERIOD_SECONDS ]]; then 281 | echo $line >> images.reap.tmp 282 | fi 283 | done 284 | comm -23 images.reap.tmp images.used | grep -E -v -f $EXCLUDE_IDS_FILE > images.reap || true 285 | 286 | # Use -f flag on docker rm command; forces removal of images that are in Dead 287 | # status or give errors when removing. 288 | FORCE_CONTAINER_FLAG="" 289 | if [[ $FORCE_CONTAINER_REMOVAL -gt 0 ]]; then 290 | FORCE_CONTAINER_FLAG="-f" 291 | fi 292 | 293 | # Remove associated volume, so that we won't create new orphan volumes. 294 | if [[ $REMOVE_ASSOCIATED_VOLUME -gt 0 ]]; then 295 | if [[ -z $FORCE_CONTAINER_FLAG ]]; then 296 | FORCE_CONTAINER_FLAG="-v" 297 | else 298 | FORCE_CONTAINER_FLAG=$FORCE_CONTAINER_FLAG"v" 299 | fi 300 | fi 301 | # Reap containers. 302 | if [[ $DRY_RUN -gt 0 ]]; then 303 | container_log "The following container would have been removed" containers.reap 304 | else 305 | container_log "Removing containers" containers.reap 306 | xargs -n 1 $DOCKER rm $FORCE_CONTAINER_FLAG --volumes=true < containers.reap &>/dev/null || true 307 | fi 308 | 309 | # Use -f flag on docker rmi command; forces removal of images that have multiple tags 310 | FORCE_IMAGE_FLAG="" 311 | if [[ $FORCE_IMAGE_REMOVAL -gt 0 ]]; then 312 | FORCE_IMAGE_FLAG="-f" 313 | fi 314 | 315 | # Reap images. 316 | if [[ $DRY_RUN -gt 0 ]]; then 317 | image_log "The following image would have been removed" images.reap 318 | else 319 | image_log "Removing image" images.reap 320 | xargs -n 1 $DOCKER rmi $FORCE_IMAGE_FLAG < images.reap &>/dev/null || true 321 | fi 322 | 323 | if [[ $REMOVE_VOLUMES -gt 0 ]]; then 324 | set +e 325 | $DOCKER volume ls --filter "dangling=true" -q &> /dev/null 326 | VOLUMES=$? 327 | set -e 328 | # If docker volume ls fails, then is probably not supported by either client or server 329 | if [ ! -f "$EXCLUDE_VOLUMES_IDS_FILE" ] 330 | then 331 | EXCLUDE_VOLUMES_IDS_FILE=/dev/null 332 | fi 333 | 334 | if [[ $VOLUMES -gt 0 ]]; then 335 | set +e 336 | VERSION=$($DOCKER version --format="Client: {{.Client.Version}} Server: {{.Server.Version}}" 2&>/dev/null) 337 | FORMAT=$? 338 | set -e 339 | if [[ $FORMAT -gt 0 ]]; then 340 | log "Removing volumes is not supported for Docker < 1.9.0" 341 | else 342 | MESSAGE="Removing volumes is not supported for for docker version "$($DOCKER version --format="Client: {{.Client.Version}} Server: {{.Server.Version}}") & 343 | log "$MESSAGE" 344 | fi 345 | else 346 | if [[ -z "$VOLUME_DELETE_ONLY_DRIVER" ]]; then 347 | $DOCKER volume ls --filter "dangling=true" -q | grep -v -f $EXCLUDE_VOLUMES_IDS_FILE > volumes.reap 348 | else 349 | $DOCKER volume ls --filter "dangling=true" --filter "driver=$VOLUME_DELETE_ONLY_DRIVER" -q | grep -v -f $EXCLUDE_VOLUMES_IDS_FILE > volumes.reap 350 | fi 351 | 352 | if [[ $DRY_RUN -gt 0 ]]; then 353 | volumes_log "The following volume would have been removed" volumes.reap 354 | else 355 | volumes_log "Removing volume" volumes.reap 356 | xargs -n 1 $DOCKER volume rm < volumes.reap &>/dev/null || true 357 | fi 358 | fi 359 | fi 360 | --------------------------------------------------------------------------------