Build Docker Image From Go Code

后端 未结 6 1647
鱼传尺愫
鱼传尺愫 2020-12-03 15:29

I\'m trying to build a Docker image using the Docker API and Docker Go libraries (https://github.com/docker/engine-api/). Code example:

package main
import (         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 15:56

    Combining a few of the answers, and adding how to correctly parse the returned JSON using DisplayJSONMessagesToStream.

    package main
    
    import (
        "os"
        "log"
    
        "github.com/docker/docker/api/types"
        "github.com/docker/docker/pkg/archive"
        "github.com/docker/docker/pkg/jsonmessage"
        "github.com/docker/docker/pkg/term"
        "golang.org/x/net/context"
    )
    
    // Build a dockerfile if it exists
    func Build(dockerFilePath, buildContextPath string, tags []string) {
    
        ctx := context.Background()
        cli := getCLI()
    
        buildOpts := types.ImageBuildOptions{
            Dockerfile: dockerFilePath,
            Tags:       tags,
        }
    
        buildCtx, _ := archive.TarWithOptions(buildContextPath, &archive.TarOptions{})
    
        resp, err := cli.ImageBuild(ctx, buildCtx, buildOpts)
        if err != nil {
            log.Fatalf("build error - %s", err)
        }
        defer resp.Body.Close()
    
        termFd, isTerm := term.GetFdInfo(os.Stderr)
        jsonmessage.DisplayJSONMessagesStream(resp.Body, os.Stderr, termFd, isTerm, nil)
    }
    

    I've left our a few convenience functions like getCLI but I'm sure you have your own equivalents.

提交回复
热议问题