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.
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{})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With