我试图捕获我在附加的Docker容器上运行的命令的输出,但我无法弄清楚如何从ls
这样的命令获取输出。
下面的代码产生了这个:
[[<root@098c455d93ff:/# ls; ><echo 1987a><6ee-2aad-4713-831a-f8102bfde4b7 $?
><bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr
>]]
而我正试图只获得这个:
[[<bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr
>]]
代码:
'use strict'
Docker = require 'dockerode'
uuid = require 'node-uuid'
async = require 'async'
os = require 'os'
fs = require 'fs'
class Make
d: new Docker
host: '192.168.59.103'
protocol: 'https'
port: 2376
ca: fs.readFileSync(process.env.DOCKER_CERT_PATH + '/ca.pem')
cert: fs.readFileSync(process.env.DOCKER_CERT_PATH + '/cert.pem')
key: fs.readFileSync(process.env.DOCKER_CERT_PATH + '/key.pem')
output: ''
run: (cmd, callback) ->
pid = uuid.v4()
command = cmd + '; echo ' + pid + ' $?' + os.EOL
@stream.on 'readable', =>
data = @stream.read()
# console.log data
# look for exit code
matchExit = data.match /(^[A-Za-z0-9-]{36})\s(\d+)$/m
if matchExit isnt null and matchExit[1] is pid
if matchExit[2] isnt '0'
console.error 'Exit code: %d: %s', matchExit[2], command
@stream.removeAllListeners 'readable'
return callback()
# look for command output
matchOutput = data.match /([A-Za-z0-9-]{36})/
if matchOutput is null
@output += '<' + data + '>'
@stream.write command
setup: (callback) ->
async.series [
# create
(callback) =>
options =
Image: 'ubuntu'
Tty: true
# AttachStdin: true
# AttachStdout: true
AttachStderr: true
OpenStdin: true
# StdinOnce: false
@d.createContainer options, (err, @container) =>
callback err
# attach
, (callback) =>
options =
stream: true
stdin: true
stdout: true
stderr: true
@container.attach options, (err, @stream) =>
return callback err if err?
@stream.setEncoding 'utf8'
callback()
# start
, (callback) =>
@container.start callback
], callback
build: (callback) ->
cmds = [
'ls'
# 'mkdir test'
# 'cd test'
# 'echo "hello world" > hello.txt'
# 'cat hello.txt'
]
runner = (cmd, callback) => @run cmd, callback
async.eachSeries cmds, runner, callback
make = new Make()
make.setup (err) ->
console.error err if err?
make.build ->
console.log '[[' + make.output + ']]'
make.stream.end()
答案 0 :(得分:0)
如果是你想要的记录功能,我会用一些例子写下这个要点。 https://gist.github.com/afolarin/a2ac14231d9079920864
如果使用v1.3,您可能会考虑的另一件事是docker exec
命令,您可以使用该命令将新进程插入到正在运行的容器中。