forked from diy-cloud/compositor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (84 loc) · 1.91 KB
/
main.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
)
func main() {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
reader, err := cli.ImagePull(ctx, "docker.io/yeasy/simple-web", types.ImagePullOptions{})
if err != nil {
panic(err)
}
defer reader.Close()
io.Copy(os.Stdout, reader)
hostConfig := &container.HostConfig{
AutoRemove: true,
PortBindings: nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "0.0.0.0",
HostPort: "8080",
},
},
},
}
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: "yeasy/simple-web",
ExposedPorts: nat.PortSet{
"80/tcp": struct{}{},
},
Tty: false,
}, hostConfig, nil, 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})
if err != nil {
panic(err)
}
go func() {
for {
scanner := bufio.NewReader(out)
line, _, err := scanner.ReadLine()
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
fmt.Printf("[%s-%s]: %s\n", "simple-web", resp.ID[:10], string(line[8:]))
}
}()
terminalChan := make(chan os.Signal, 1)
signal.Notify(terminalChan, os.Interrupt, os.Signal(syscall.SIGTERM))
<-terminalChan
if err := cli.ContainerStop(ctx, resp.ID, nil); err != nil {
panic(err)
}
images, err := cli.ImageList(ctx, types.ImageListOptions{})
if err != nil {
panic(err)
}
for _, image := range images {
fmt.Println(image.ID[:10])
fmt.Println(image.RepoDigests)
fmt.Println(image.RepoTags)
fmt.Println("---")
}
}