dockerode icon indicating copy to clipboard operation
dockerode copied to clipboard

Copy file from container to host

Open Tzvetelin88 opened this issue 3 years ago • 1 comments

Is there a way to copy data from a running container to host, in this case to copy a file.

What I found as some possible solutions:

  1. Using docker.exec(). To execute a command like "cat ./file.log" - and send back output as stdout. link, but didn't work.

  2. To use .getArchive and .putArchive - but it seems this works only with *.tar files.

Tzvetelin88 avatar Dec 16 '21 14:12 Tzvetelin88

He is my working example. If you have some recommendation to make it better will be tankfull:

       const docker = new Docker({ socketPath: process.platform === 'win32' ? '//./pipe/docker_engine' : '/var/run/docker.sock' });
       const container = docker.getContainer("docker_id");
        
       const newStream = require('stream');

        const stdoutStream = fs.createWriteStream("./test.log", {flags:'a'});

        const options = {
          Cmd: ['cat', 'catch_me.log'],
          WorkingDir: "/var/log/service",
          Tty: false,
          AttachStdout: true,
          AttachStderr: true,
          AttachStdin: true
        };

        await new Promise((resolve, reject) => {
          container.exec(options, function(err, exec) {
            if (err) {
              reject('Container exec failed!')
              return;
            }
            if (exec) {
              exec.start({ hijack: true}, function(err: any, stream: any) {
                if (err) {
                  reject('Container start execution failed!')
                  return;
                };

                const stdout = new newStream.PassThrough();
                const stderr = new newStream.PassThrough();
                container.modem.demuxStream(stream, stdout, stderr);

                stdout.on('data', function (chunk: Buffer) {
                   stdoutStream.write(chunk);
                });

                stream.on('end', () => {
                  stdoutStream.close();
                  console.log('Close stream')
                  resolve('Ready')
                });

                exec.inspect(function(err, data) {
                  if (err) {
                    reject('Execution Inspect failed!')
                    return;
                  };
                });
              });
            }
          });
        })

Tzvetelin88 avatar Dec 17 '21 15:12 Tzvetelin88

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Open a new issue if needed.

stale[bot] avatar Jun 21 '23 00:06 stale[bot]

+1

Heartnett avatar Oct 23 '23 09:10 Heartnett