Created
July 23, 2020 01:56
-
-
Save x893675/916ed3c40ddb98d8a387bd087e81b346 to your computer and use it in GitHub Desktop.
docker sdk
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 | |
// docker client package version error, always import github.com/docker/docker v1.13.1 | |
// Issue: https://github.com/moby/moby/issues/39302 | |
import ( | |
"context" | |
"fmt" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/api/types/container" | |
"github.com/docker/docker/client" | |
"github.com/docker/docker/pkg/stdcopy" | |
"io" | |
"os" | |
) | |
const DockerHost = "tcp://localhost:2376" | |
func main() { | |
ctx := context.Background() | |
cli, err := client.NewClientWithOpts(client.WithHost(DockerHost), client.WithAPIVersionNegotiation()) | |
if err != nil { | |
panic(err) | |
} | |
images, err := cli.ImageList(ctx, types.ImageListOptions{}) | |
if err != nil { | |
panic(err) | |
} | |
for _, image := range images { | |
fmt.Println(image.RepoTags) | |
} | |
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: false, | |
}, 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