Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker Golang API create a container with files from memory

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.

like image 223
AWildTyphlosion Avatar asked Apr 12 '17 18:04

AWildTyphlosion


Video Answer


1 Answers

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{})
like image 101
TimSatke Avatar answered Sep 30 '22 15:09

TimSatke