forked from vbauerster/60-days-of-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattach.go
62 lines (57 loc) · 1.46 KB
/
attach.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"io"
"log"
"os"
"github.com/fsouza/go-dockerclient"
)
// Run creates and start a container ataching writers to stdout and stderr
func Run(client *docker.Client, stdout, stderr io.Writer) string {
// create a container
container, err := client.CreateContainer(docker.CreateContainerOptions{
Name: "teste-hello",
Config: &docker.Config{
Cmd: []string{"/bin/bash", "-c", "for i in {1..10}; do echo $i; sleep 2; done"},
Image: "debian:8",
StdinOnce: true,
OpenStdin: true,
},
})
if err != nil {
log.Fatal(err)
}
// start the created container
err = client.StartContainer(container.ID, nil)
if err != nil {
log.Fatal("StartContainer:", err)
}
// attach to container binding writers to stdout and stderr
// Note: logs are true because we can lost some computation done before attach
_, err = client.AttachToContainerNonBlocking(docker.AttachToContainerOptions{
Container: container.ID,
RawTerminal: true,
Stream: true,
Stdin: true,
Stdout: true,
Stderr: true,
Logs: true,
OutputStream: stdout,
ErrorStream: stderr,
})
// return container id
return container.ID
}
func main() {
// connect to local socket
endpoint := "unix:///var/run/docker.sock"
client, err := docker.NewClient(endpoint)
if err != nil {
panic(err)
}
id := Run(client, os.Stdout, os.Stderr)
// wait computation inside container
_, err = client.WaitContainer(id)
if err != nil {
return
}
}