Skip to content

Instantly share code, notes, and snippets.

@loa
Created September 29, 2015 06:17
Show Gist options
  • Select an option

  • Save loa/abd0c7d19f14b96930ad to your computer and use it in GitHub Desktop.

Select an option

Save loa/abd0c7d19f14b96930ad to your computer and use it in GitHub Desktop.
Golang docker directly
// $ go run golang-docker-directly.go && docker run -it --rm golang-docker-directly
package main
import (
"archive/tar"
"bytes"
"fmt"
"log"
"os/exec"
)
func createContext() (*bytes.Buffer, error) {
// Create a buffer to write our archive to.
buf := new(bytes.Buffer)
// Create a new tar archive.
tw := tar.NewWriter(buf)
// Add some files to the archive.
var files = []struct {
Name, Body string
}{
{"Dockerfile", "FROM busybox\nADD gopher.txt /\nCMD cat /gopher.txt"},
{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo\n"},
}
for _, file := range files {
hdr := &tar.Header{
Name: file.Name,
Mode: 0600,
Size: int64(len(file.Body)),
}
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
if _, err := tw.Write([]byte(file.Body)); err != nil {
return nil, err
}
}
// Make sure to check the error on Close.
if err := tw.Close(); err != nil {
return nil, err
}
return buf, nil
}
func build(name string, context *bytes.Buffer) error {
cmd := exec.Command("docker", "build", "-t", name, "-")
// Open the tar archive for reading.
cmd.Stdin = bytes.NewReader(context.Bytes())
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return err
}
fmt.Println(out.String())
return nil
}
func main() {
context, err := createContext()
if err != nil {
log.Fatal(err)
}
err = build("golang-docker-directly", context)
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment