Created
December 20, 2017 16:40
-
-
Save maurorappa/8be045a62992839b6d91a7421f8f7f89 to your computer and use it in GitHub Desktop.
Docker cleanup tool for old versions
This file contains hidden or 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
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/client" | |
"golang.org/x/net/context" | |
) | |
var containers_tobedeleted = map[string]string{} | |
func main() { | |
dry_run := flag.Bool("d", false, "Dry Run, don't clean any container") | |
all := flag.Bool("a", true, "Clean all containers (default), if false cleans only the inactive ones") | |
base_image := flag.Bool("i", false, "Clean also the related container image ") | |
kill_image := flag.String("k", "", "Clean all the containers based on this image") | |
flag.Parse() | |
cli, err := client.NewEnvClient() | |
if err != nil { | |
panic(err) | |
} | |
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true}) | |
if err != nil { | |
panic(err) | |
} | |
if len(containers) == 0 { | |
fmt.Println("No running containers!\n(doublecheck with `docker ps`)") | |
os.Exit(0) | |
} | |
fmt.Println("\nContainers found on this host:") | |
for _, container := range containers { | |
r, err := cli.ContainerInspect(context.Background(), container.ID) | |
if err != nil { | |
panic(err) | |
} | |
container_id := container.ID[:12] | |
base_image := r.Image[7:19] | |
running := r.State.Running | |
fmt.Printf("%s - %s - %s\n",container_id,r.Name[1:],base_image) | |
if ! *all { | |
if ! running { | |
containers_tobedeleted[container_id] = base_image | |
} | |
} else { | |
containers_tobedeleted[container_id] = base_image | |
} | |
if (base_image == *kill_image) { | |
containers_tobedeleted[container_id] = base_image | |
} | |
} | |
if *dry_run { | |
fmt.Println("Dry run, exiting") | |
os.Exit(0) | |
} | |
if len(containers_tobedeleted) > 0 { | |
for c,i := range containers_tobedeleted { | |
fmt.Printf("Killing container: %s (img %s)\n",c,i) | |
err := cli.ContainerRemove(context.Background(), c, types.ContainerRemoveOptions{Force: true, RemoveVolumes: true}) | |
if err != nil { | |
panic(err) | |
} | |
} | |
for _,i := range containers_tobedeleted { | |
if *base_image { | |
fmt.Printf("Killing image: %s\n",i) | |
_,err := cli.ImageRemove(context.Background(), i, types.ImageRemoveOptions{Force: true, PruneChildren: true}) | |
if err != nil { | |
fmt.Printf("Failed to remove this image: %s\n", err) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you need to specify this environment variable DOCKER_API_VERSION to ensure the utility and the docker daemon use the same API version.