Created
June 29, 2018 07:41
-
-
Save miguelmota/4980b18d750fb3b1eb571c3e207b1b92 to your computer and use it in GitHub Desktop.
Golang docker pull image and run container
This file contains hidden or 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 ( | |
"io" | |
"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() { | |
ctx := context.Background() | |
cli, err := client.NewEnvClient() | |
if err != nil { | |
panic(err) | |
} | |
reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{}) | |
if err != nil { | |
panic(err) | |
} | |
io.Copy(os.Stdout, reader) | |
resp, err := cli.ContainerCreate(ctx, &container.Config{ | |
Image: "alpine", | |
Cmd: []string{"echo", "hello world"}, | |
Tty: true, | |
}, 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) | |
} | |
io.Copy(os.Stdout, out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment