Created
July 17, 2019 03:13
-
-
Save sempr/3887f88f346e7d527475157efb97f13e to your computer and use it in GitHub Desktop.
Try Using Golang Docker API
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" | |
"io" | |
"os" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/api/types/container" | |
"github.com/docker/docker/api/types/mount" | |
"github.com/docker/docker/api/types/network" | |
"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) | |
reader, err := cli.ImagePull(ctx, "busybox", types.ImagePullOptions{}) | |
if err != nil { | |
panic(err) | |
} | |
io.Copy(os.Stdout, reader) | |
resp, err := cli.ContainerCreate(ctx, &container.Config{ | |
Image: "busybox", | |
Cmd: []string{"sh", "-c", "echo hello world >/host/output/hello.txt"}, | |
NetworkDisabled: true, | |
}, &container.HostConfig{ | |
ReadonlyRootfs: true, | |
AutoRemove: true, | |
Resources: container.Resources{Memory: 1 << 30, MemorySwap: 1 << 30}, | |
Mounts: []mount.Mount{ | |
{ | |
Type: mount.TypeBind, | |
Source: "/tmp", | |
Target: "/host/tmp", | |
ReadOnly: true, | |
}, | |
{ | |
Type: mount.TypeBind, | |
Source: "/tmp/output", | |
Target: "/host/output", | |
ReadOnly: false, | |
}, | |
}, | |
}, &network.NetworkingConfig{}, "") | |
if err != nil { | |
panic(err) | |
} | |
if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { | |
panic(err) | |
} | |
out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true}) | |
if err != nil { | |
panic(err) | |
} | |
stdcopy.StdCopy(os.Stdout, os.Stderr, out) | |
statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning) | |
select { | |
case err := <-errCh: | |
if err != nil { | |
panic(err) | |
} | |
case <-statusCh: | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment