-
Notifications
You must be signed in to change notification settings - Fork 12
/
node-docker-server.js
59 lines (53 loc) · 1.4 KB
/
node-docker-server.js
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
const WebSocket = require('ws');
const Docker = require('node-docker-api').Docker;
const wss = new WebSocket.Server({ port: 9000 });
console.log('[node-docker-server] is running');
let _container;
const getContainer = async (docker, Image) => {
if (_container) {
return _container;
} else {
const containers = await docker.container.list();
containers.forEach((item) => {
if (item.data.Image.includes(Image)) {
_container = item;
return item;
}
});
return _container;
}
};
const docker = new Docker({ socketPath: '/var/run/docker.sock' });
wss.on('connection', (ws) => {
ws.on('message', async (msg) => {
try {
const { type } = JSON.parse(msg);
if (type === 'logs') {
const container = await getContainer(docker, 'w3bstream');
if (container) {
const stream = await container.logs({
follow: true,
stdout: true,
stderr: true
});
stream.on('data', (info) => {
const log = info.toString();
ws.send(
JSON.stringify({
type: 'logs',
data: log
})
);
});
} else {
ws.send(
JSON.stringify({
type: 'logs',
data: 'No "w3bstream" container found'
})
);
}
}
} catch (error) {}
});
});