Created
January 18, 2017 23:30
-
-
Save icereval/d0ba3fe1cd531a20e9e1f048be69003e to your computer and use it in GitHub Desktop.
Kubernetes Cleanup DaemonSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apiVersion: extensions/v1beta1 | |
kind: DaemonSet | |
metadata: | |
name: cleanup | |
labels: | |
tier: system | |
app: cleanup | |
version: v3 | |
spec: | |
template: | |
metadata: | |
labels: | |
name: cleanup | |
spec: | |
containers: | |
- name: cleanup | |
image: docker:1.11 | |
securityContext: | |
privileged: true | |
command: [ | |
'/bin/sh', | |
'-c', | |
' | |
apk add --update bash && rm -rf /var/cache/apk/* && | |
echo "$$DOCKER_CLEANUP" > /docker-cleanup.sh && | |
chmod +x /docker-cleanup.sh && | |
/docker-cleanup.sh | |
' | |
] | |
env: | |
- name: DOCKER_CLEANUP | |
value: | | |
#!/bin/bash | |
# Source: https://github.com/paralin/KubeCleanup | |
echo "Waiting ~30s for pods to be initially scheduled..." | |
sleep 30s | |
echo "Starting cleanup loop..." | |
while true; do | |
# WARNING: killing init containers causes pods to die, disabled for now. | |
# echo "$(date +%s) Cleaning up exited containers..." | |
# docker ps -a | grep Exit | cut -d ' ' -f 1 | xargs docker rm | |
echo "$(date +%s) Cleaning up dangling images..." | |
docker images --no-trunc -q -f dangling=true | xargs -r docker rmi | |
echo "$(date +%s) Cleaning up unused images..." | |
images=($(docker images | tail -n +2 | awk '{print $1":"$2}')) | |
containers=($(docker ps -a | tail -n +2 | awk '{print $2}')) | |
containers_reg=" ${containers[*]} " | |
remove=() | |
for item in ${images[@]}; do | |
if [[ ! $containers_reg =~ " $item " ]]; then | |
remove+=($item) | |
fi | |
done | |
remove_images=" ${remove[*]} " | |
echo ${remove_images} | xargs -r docker rmi | |
echo "$(date +%s) Done, waiting another 30 mins before next cleanup..." | |
sleep 30m | |
done | |
volumeMounts: | |
- name: docker | |
mountPath: /var/run/docker.sock | |
volumes: | |
- name: docker | |
hostPath: | |
path: /var/run/docker.sock |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment