/
get-container-log.ts
120 lines (110 loc) · 2.72 KB
/
get-container-log.ts
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { Client } from "../src/v1.41";
import * as ApiClientImpl from "../src/api-client-impl";
import * as fs from "fs";
import * as path from "path";
import * as stream from "stream";
import { demuxStream } from "./utils";
const main = async () => {
const apiClientImpl = ApiClientImpl.create({
socketPath: "/var/run/docker.sock",
});
const client = new Client(apiClientImpl, "/v1.41");
fs.mkdirSync("debug", { recursive: true });
const currentDir = path.resolve("example");
const containerName = "create-from-api";
const alreadyUsedContainers = await client.ContainerList({
parameter: {
all: true,
filters: `name=${containerName}`,
},
});
const removeTasks = alreadyUsedContainers.map(async container => {
if (!container.Id) {
return;
}
if (container.State === "running") {
await client.ContainerStop({
parameter: {
id: container.Id,
},
});
}
await client.ContainerDelete({
parameter: {
id: container.Id,
},
});
});
await Promise.all(removeTasks);
const filename1 = "debug/docker-create-container.json";
const container = await client.ContainerCreate({
headers: {
"Content-Type": "application/json",
},
parameter: {
name: containerName,
},
requestBody: {
Image: "golang:1.17",
WorkingDir: "/app",
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
OpenStdin: true,
Cmd: ["ls"],
HostConfig: {
Mounts: [
{
Type: "bind",
Source: currentDir,
Target: "/app",
},
],
},
},
});
fs.writeFileSync(filename1, JSON.stringify(container, null, 2), "utf-8");
console.log(`Output: ${filename1}`);
await client.ContainerStart({
parameter: {
id: container.Id,
},
});
const logStream = new stream.PassThrough();
const logFileStream = fs.createWriteStream("debug/docker-container.log", "utf-8");
logStream.on("data", chunk => {
console.log(chunk.toString("utf-8"));
});
await client.ContainerLogs(
{
headers: {
Accept: "application/json",
},
parameter: {
id: container.Id,
stdout: true,
stderr: true,
follow: true,
tail: "all",
},
},
{
isStream: true,
onResponse: res => {
demuxStream(res, logStream, logStream);
demuxStream(res, logFileStream, logFileStream);
res.on("data", chunks => {
logStream.write(chunks);
});
res.on("end", () => {
logStream.end();
logFileStream.end();
});
},
},
);
};
main().catch(error => {
console.error(error);
process.exit(1);
});