Skip to content

Instantly share code, notes, and snippets.

@we4tech
Created June 4, 2019 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save we4tech/adf6beb55d814e6f8a83318593f8a9fe to your computer and use it in GitHub Desktop.
Save we4tech/adf6beb55d814e6f8a83318593f8a9fe to your computer and use it in GitHub Desktop.
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