Last active
September 26, 2019 12:51
-
-
Save donvito/99db84fffd24c4b6f6cf1340b0c4bd48 to your computer and use it in GitHub Desktop.
Go code to run a container and retrieve stdout
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 ( | |
"context" | |
"os" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/api/types/container" | |
"github.com/docker/docker/client" | |
"github.com/docker/docker/pkg/stdcopy" | |
) | |
func main() { | |
ctx := context.Background() | |
cli, err := client.NewClientWithOpts(client.FromEnv) | |
if err != nil { | |
panic(err) | |
} | |
cli.NegotiateAPIVersion(ctx) | |
resp, err := cli.ContainerCreate(ctx, &container.Config{ | |
Image: "go-multi-stage", | |
}, nil, nil, "") | |
if err != nil { | |
panic(err) | |
} | |
if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { | |
panic(err) | |
} | |
statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning) | |
select { | |
case err := <-errCh: | |
if err != nil { | |
panic(err) | |
} | |
case <-statusCh: | |
} | |
out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true}) | |
if err != nil { | |
panic(err) | |
} | |
stdcopy.StdCopy(os.Stdout, os.Stderr, out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment