docker SDK 的基本学习

 

```

package main

import(
    "fmt"
    "context"
    "os"
    "io"
    // "reflect"
    "time"
"github.com/docker/docker/client"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
// "github.com/docker/docker/pkg/stdcopy"
)

func main(){
    t3:=time.Now()
    fmt.Println("t3",t3)
    fmt.Println("test")
    ctx := context.Background()
    fmt.Println("ctx",ctx)
    cli,err := client.NewClientWithOpts(client.FromEnv)
    if err!=nil{
        panic(err)
    }
    fmt.Println(cli)
    cli.NegotiateAPIVersion(ctx) //切换到于当前能够本机运行的API接口
    fmt.Println(cli)
    reader,err:=cli.ImagePull(ctx,"golang:alpine",types.ImagePullOptions{})
    if err!=nil{
        panic(err)
    }
    fmt.Println(reader)
    writer,err:=io.Copy(os.Stdout,reader)
    if err!=nil{
        panic(err)
    }
    fmt.Println(writer)

    //创建一个容器
    resp, err := cli.ContainerCreate(ctx, &container.Config{
        Hostname :"nodetest",
        Image: "node",
        Cmd: []string{"node", "/workspace/test.js"},
        Tty: true,
    }, &container.HostConfig{
        Binds:[]string{"/home/ysm/nodetest:/workspace"},
    }, nil, "")
    if err!=nil{
        panic(err)
    }
    fmt.Println(resp.ID)
    fmt.Println(resp)

    //运行一个容器
    err = cli.ContainerStart(ctx,resp.ID, types.ContainerStartOptions{})
    if err!=nil{
        panic(err)
    }
    fmt.Println("this is a problem")

    t1:= time.Now()
    fmt.Println("t1",t1)

    //容器状态
    // container.WaitConditionNotRunning 等待不运行

    // statusCh,errCh:= cli.ContainerWait(ctx,resp.ID,container.WaitConditionNotRunning )
    // select{
    // case err:=<-errCh:
    //  if err!=nil{
    //      panic(err)
    //  }
    // case x,ok:=<-statusCh:
    //  fmt.Println("zhe ge shi",reflect.TypeOf(statusCh))
    //  if !ok{
    //      fmt.Println("zhe shi ge bu he ge de ren")
    //  }else{
    //      fmt.Println(x.StatusCode)
    //  }
    // }

    t2 := time.Now()
    fmt.Println("t2",t2)
    if t2.Sub(t1)>6{
        fmt.Println("chao shi jian")
        err = cli.ContainerStop(ctx,resp.ID,nil)
        if err!=nil{
            panic(err)
        }
        err = cli.ContainerRemove(ctx,resp.ID,types.ContainerRemoveOptions{Force:true})
        if err!=nil{
            panic(err)
        }
        return
    }

    //只有当容器结束之后才能获取到数据
    out,err := cli.ContainerLogs(ctx,resp.ID,types.ContainerLogsOptions{ShowStdout:true,ShowStderr:true})
    if err!=nil{
        panic(err)
    }
    fmt.Println(out)
    io.Copy(os.Stdout,out)
}
```
posted @ 2019-07-20 22:25  Myuniverse  阅读(1458)  评论(0编辑  收藏  举报