Copy a directory recursively from a container to host using docker client go library

Viewed 191

I want to recursively copy a directory from a container on the host.

I'm new to golang and fully aware about docker cp as an alternative but i need to do it via client go library of docker

I was able to copy a file from a container to host, but unable to do so for directories.

Here's what i have till now

package main

import (
    "archive/tar"
    "context"
    "fmt"
    "io"
    "os"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/container"
    "github.com/docker/docker/client"
)

func main() {
    sourcePath := "/test/file.txt"
    destinationPath := "/home/user/"
    cli, err := client.NewClientWithOpts(client.FromEnv)

    if err != nil {
        panic(err)
    }
        myContainer, err := cli.ContainerCreate(context.Background(), &container.Config{
        Image: "alpine:test",
     }, nil, nil, nil,"")
    if err != nil {
        fmt.Println(err.Error(), "error occurred")
    }
    tarStream, _, err := cli.CopyFromContainer(context.Background(), myContainer.ID, sourcePath)
    if err != nil {
        fmt.Println("something went wrong", err)
    }
    tr := tar.NewReader(tarStream)
    if _, err := tr.Next(); err != nil {
            panic(err)
    }

    dst, err := os.Create(destinationPath + "file.txt")
    if err != nil {
        fmt.Println("error occurred", err)
    }
    defer dst.Close()

    _, err = io.Copy(dst, tr)
    if err != nil {
        fmt.Println("error", err)
    }
    cli.ContainerRemove(context.Background(), myContainer.ID, types.ContainerRemoveOptions{})
}

But actually i want to copy the whole directory inside the container /test/ recursively on the host.

0 Answers
Related