-
-
Save hardeepnarang10/66d7a99793ff8eed92f4740aa0cf583b to your computer and use it in GitHub Desktop.
Copy file from Docker image to standard output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"archive/tar" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"os" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/api/types/container" | |
"github.com/docker/docker/client" | |
"golang.org/x/net/context" | |
) | |
func main() { | |
if len(os.Args) != 3 { | |
fmt.Fprintf(os.Stderr, "Usage: %s IMAGE FILE\n", os.Args[0]) | |
os.Exit(1) | |
} | |
imageName := os.Args[1] | |
filePath := os.Args[2] | |
ctx := context.Background() | |
cli, err := client.NewEnvClient() | |
if err != nil { | |
panic(err) | |
} | |
out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{}) | |
if err != nil { | |
panic(err) | |
} | |
defer out.Close() | |
if _, err := ioutil.ReadAll(out); err != nil { | |
panic(err) | |
} | |
info, err := cli.ContainerCreate(ctx, &container.Config{ | |
Image: imageName, | |
}, nil, nil, "") | |
if err != nil { | |
panic(err) | |
} | |
tarStream, _, err := cli.CopyFromContainer(ctx, info.ID, filePath) | |
if err != nil { | |
panic(err) | |
} | |
tr := tar.NewReader(tarStream) | |
if _, err := tr.Next(); err != nil { | |
panic(err) | |
} | |
io.Copy(os.Stdout, tr) | |
if err := cli.ContainerRemove(ctx, info.ID, types.ContainerRemoveOptions{}); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment