Skip to content

Instantly share code, notes, and snippets.

@dhanush
Last active March 21, 2020 06:14
Show Gist options
  • Save dhanush/f96c547493582587ab9f20f694eba47f to your computer and use it in GitHub Desktop.
Save dhanush/f96c547493582587ab9f20f694eba47f to your computer and use it in GitHub Desktop.
Go file to build a docker image
func BuildImage(dockerBuildCtxDir, tagName string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(300)*time.Second)
defer cancel()
dockerFileTarReader, err := tarDirectory(dockerBuildCtxDir)
//this above method will create a tar file from the directory passed in. The return has to be of type io.Reader
if err != nil {
log.Printf("Error in taring the docker root folder - %s", err.Error())
return err
}
buildArgs := make(map[string]*string)
// add any build args if you want to
buildArgs["ENV"] = os.Getenv("GO_ENV")
resp, err := cli.ImageBuild(
ctx,
dockerFileTarReader,
types.ImageBuildOptions{
Dockerfile: "Dockerfile",
Tags: []string{tagName},
NoCache: true,
Remove: true,
BuildArgs: buildArgs,
}) //cli is the docker client instance created from the engine-api
if err != nil {
log.Println(err, " :unable to build docker image")
return err
}
return writeToLog(resp.Body)
}
//writes from the build response to the log
func writeToLog(reader io.ReadCloser) error {
defer reader.Close()
rd := bufio.NewReader(reader)
for {
n, _, err := rd.ReadLine()
if err != nil && err == io.EOF {
break
} else if err != nil {
return err
}
log.Println(string(n))
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment