Skip to content

Instantly share code, notes, and snippets.

@frikky
Created June 18, 2019 08:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frikky/e2efcea6c733ea8d8d015b7fe8a91bf6 to your computer and use it in GitHub Desktop.
Save frikky/e2efcea6c733ea8d8d015b7fe8a91bf6 to your computer and use it in GitHub Desktop.
Stop and remove a docker container with Golang
package main
import (
"log"
"fmt"
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
// Stop and remove a container
func stopAndRemoveContainer(client *client.Client, containername string) error {
ctx := context.Background()
if err := client.ContainerStop(ctx, containername, nil); err != nil {
log.Printf("Unable to stop container %s: %s", containername, err)
}
removeOptions := types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
}
if err := client.ContainerRemove(ctx, containername, removeOptions); err != nil {
log.Printf("Unable to remove container: %s", err)
return err
}
return nil
}
func main() {
client, err := client.NewEnvClient()
if err != nil {
fmt.Printf("Unable to create docker client: %s", err)
}
// Stops and removes a container
stopAndRemoveContainer(client, "containername")
}
@Akilan1999
Copy link

Thanks a lot,
Really useful !

@andreafalzetti
Copy link

Thank you for sharing!

@realtemirov
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment