使用Docker Golang API从内存中创建一个包含文件的容器。

huangapple go评论78阅读模式
英文:

Docker Golang API create a container with files from memory

问题

目前,使用golang api将文件放入容器中,我首先必须创建容器,然后使用CopyToContainer函数(示例如下)。

是否可以在创建容器时指定文件,而无需首先在文件系统上拥有这些文件?

示例1)

func main() {
    cli, err := client.NewEnvClient()
    if err != nil {
        panic(err)
    }

    resp, err := cli.ContainerCreate(context.Background(),
        &container.Config{
            Image: "alpine",
            Cmd:   []string{"ls", "/"},
        }, nil, nil, "testContainer")
    if err != nil {
        panic(err)
    }

    fmt.Printf("Created: %v\n", resp.ID)

    cli.CopyToContainer(context.Background(), resp.ID, "/", getTar(), types.CopyToContainerOptions{})
}

func getTar() io.Reader {
    ...
}

编辑:

  • 代码间距。
英文:

Currently, to get files into a container using the golang api I first must create the container and then use the CopyToContainer function (Example Below).

Is it possible to create a container and specify files for it to have at create time, without having the files first on the file system?

Example 1)

func main() {
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	resp, err := cli.ContainerCreate(context.Background(),
    	&container.Config{
    		Image: "alpine",
	    	Cmd:   []string{"ls", "/"},
    	}, nil, nil, "testContainer")
    if err != nil {
    	panic(err)
    }

    fmt.Printf("Created: %v\n", resp.ID)

	cli.CopyToContainer(context.Background(), resp.ID, "/", getTar(),types.CopyToContainerOptions{})
}

func getTar() io.Reader {
    ...
}

EDIT:

  • Code spacing.

答案1

得分: 2

我找到了这个解决方案,但是我无法让文件显示在容器中。你可以尝试一下,如果对你有用的话,请告诉我!

var buf bytes.Buffer
tw := tar.NewWriter(&buf)
err = tw.WriteHeader(&tar.Header{
    Name: filename,            // 文件名
    Mode: 0777,                // 权限
    Size: int64(len(content)), // 文件大小
})
if err != nil {
    return nil, fmt.Errorf("docker copy: %v", err)
}
tw.Write([]byte(content))
tw.Close()

// 将 &buf 作为 CopyToContainer 的 content 参数
cli.CopyToContainer(context.Background(), resp.ID, "/", &buf, types.CopyToContainerOptions{})
英文:

I found this solution, but I can't get the file to show up in the container. Try it and let me know if it works for you!

var buf bytes.Buffer
tw := tar.NewWriter(&buf)
err = tw.WriteHeader(&tar.Header{
	Name: filename,            // filename
	Mode: 0777,                // permissions
	Size: int64(len(content)), // filesize
})
if err != nil {
	return nil, fmt.Errorf("docker copy: %v", err)
}
tw.Write([]byte(content))
tw.Close()

// use &buf as argument for content in CopyToContainer
cli.CopyToContainer(context.Background(), resp.ID, "/", &buf,types.CopyToContainerOptions{})

huangapple
  • 本文由 发表于 2017年4月13日 02:10:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/43376740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定