docker SDK 的基本学习

Posted myuniverse

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.ContainerRemoveOptionsForce:true)
        if err!=nil
            panic(err)
        
        return
    

    //只有当容器结束之后才能获取到数据
    out,err := cli.ContainerLogs(ctx,resp.ID,types.ContainerLogsOptionsShowStdout:true,ShowStderr:true)
    if err!=nil
        panic(err)
    
    fmt.Println(out)
    io.Copy(os.Stdout,out)
```

以上是关于docker SDK 的基本学习的主要内容,如果未能解决你的问题,请参考以下文章

docker学习基本命令

Docker学习一: 基本概念

Docker学习__基本概念

Docker构建抱怨它无法找到nuget fallback包文件夹

Docker 学习笔记Docker 相关概念,基本操作

Docker学习--docker的基本认识