go使用docker sdk停止和删除docker
- 代码
- 参考
代码
package mainimport ("context""fmt""github.com/docker/cli/cli/connhelper""github.com/docker/docker/api/types/container""github.com/docker/docker/client""net/http"
)func main() {ctx, cancel := context.WithCancel(context.Background())defer cancel()helper, err := connhelper.GetConnectionHelper("ssh://root@0.0.0.0:22")if err != nil {panic(err)return}httpClient := &http.Client{Transport: &http.Transport{DialContext: helper.Dialer,},}cli, err := client.NewClientWithOpts(client.WithHTTPClient(httpClient),client.WithHost(helper.Host),client.WithDialContext(helper.Dialer),client.WithVersion("1.40"),)if err != nil {panic(err)return}defer cli.Close()containers, err := cli.ContainerList(ctx, container.ListOptions{All: true})if err != nil {panic(err)}for _, c := range containers {fmt.Println(c.ID)err := cli.ContainerStop(ctx, c.ID, container.StopOptions{})if err != nil {fmt.Println(err)}err = cli.ContainerRemove(ctx, c.ID, container.RemoveOptions{RemoveLinks: false, RemoveVolumes: true, Force: false})if err != nil {fmt.Println(err)}}
}
参考
https://github.com/docker/docker-py/issues/2126
https://docs.docker.com/engine/api/sdk/examples/