Skip to content

Instantly share code, notes, and snippets.

@we4tech we4tech/glide.yaml
Created Jun 4, 2019

Embed
What would you like to do?
Execute docker container with bash and binds to the streams
package: we.co/tools/oktaremember
import:
- package: github.com/moby/moby
version: master
package main
import (
"context"
"fmt"
"io"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
)
var (
ctx = context.Background()
dockerCli = buildDockerClient()
imageRef = "docker.io/library/alpine"
)
func buildDockerClient() *client.Client {
cli, err := client.NewClientWithOpts(client.WithVersion("1.39"))
if err != nil {
panic(err)
}
return cli
}
func main() {
printContainerList()
pullContainer()
runContainer()
}
func pullContainer() {
out, err := dockerCli.ImagePull(ctx, imageRef, types.ImagePullOptions{})
if err != nil {
panic(err)
}
_, err = io.Copy(os.Stdout, out)
if err != nil {
panic(err)
}
}
func runContainer() {
resp, err := dockerCli.ContainerCreate(ctx, &container.Config{
Image: "alpine",
Cmd: []string{"echo", "hello world"},
}, nil, nil, "test_alpine_container")
if err != nil {
panic(err)
}
fmt.Println("Container ID", resp.ID)
if err := dockerCli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}
statusCh, errCh := dockerCli.ContainerWait(context.Background(), resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if err != nil {
panic(err)
}
case <-statusCh:
}
out, err := dockerCli.ContainerLogs(context.Background(), resp.ID, types.ContainerLogsOptions{
ShowStderr: true,
ShowStdout: true,
})
if err != nil {
panic(err)
}
_, err = io.Copy(os.Stdout, out)
if err != nil {
panic(err)
}
}
func printContainerList() {
containers, err := dockerCli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
panic(err)
}
for _, cont := range containers {
fmt.Printf("%s %s\n", cont.ID, cont.Image)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.