Skip to content

Instantly share code, notes, and snippets.

@helmutkemper
Created December 27, 2017 20:07
Show Gist options
  • Select an option

  • Save helmutkemper/c43e7c7ff8074b6b885f3a6e62fa725d to your computer and use it in GitHub Desktop.

Select an option

Save helmutkemper/c43e7c7ff8074b6b885f3a6e62fa725d to your computer and use it in GitHub Desktop.

Revisions

  1. helmutkemper created this gist Dec 27, 2017.
    66 changes: 66 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    package main

    import (
    "io"
    "os"

    "github.com/docker/docker/client"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/container"
    "golang.org/x/net/context"
    "github.com/docker/go-connections/nat"
    )

    func main() {
    ctx := context.Background()
    cli, err := client.NewEnvClient()
    if err != nil {
    panic(err)
    }

    _, err = cli.ImagePull(ctx, "ghost:latest", types.ImagePullOptions{})
    if err != nil {
    panic(err)
    }

    config := &container.Config{
    Image: "ghost",
    ExposedPorts: nat.PortSet{
    "8080/tcp": struct{}{},
    },
    }

    hostConfig := &container.HostConfig{
    PortBindings: nat.PortMap{
    "2368/tcp": []nat.PortBinding{
    {
    HostPort: "8080",
    },
    },
    },
    }
    resp, err := cli.ContainerCreate(ctx, config, hostConfig, nil, "")
    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, Details: true, Follow: true, ShowStderr: true, Timestamps: true})
    if err != nil {
    panic(err)
    }

    io.Copy(os.Stdout, out)

    statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
    select {
    case err := <-errCh:
    if err != nil {
    panic(err)
    }
    case <-statusCh:
    }
    }