Home > Back-end >  How do you run a tar command to backup a folder inside a docker container to the host?
How do you run a tar command to backup a folder inside a docker container to the host?

Time:04-03

My docker container has a directory that I want to periodically backup to the host.

I would think the command would be something like this:

docker-compose exec SERVICE_NAME tar -czf - -C /dir/to/backup . > backup.tar.gz

This should create a file called backup.tar.gz on the host.

Instead, tar detects that the output appears to be going to a terminal, and errors out:

tar: Refusing to write archive contents to terminal (missing -f option?)
tar: Error is not recoverable: exiting now

As far as I can tell, there's no --force, or anything like that for the tar command.

Is there a proper way to do this?

CodePudding user response:

Here are two ways:

  1. You can tell docker compose to not allocate a pty using the -T option.

    Example:

    docker-compose exec -T SERVICE_NAME tar -czf - -C /dir/to/backup . > backup.tar.gz
    

    The presence of a pty is how most programs, including tar, detect whether or not they are running in a terminal or attached to a pipe.

  2. You can trick tar into writing output into a terminal by using /dev/stdout in place of -.

    Example:

    $ tar -czf /dev/stdout etc/
    

    This makes tar write the archive to standard out. Do keep in mind that this restriction exists for a reason.

  • Related