How to run 2 commands with docker exec

Docker

Docker Problem Overview


I need to run 2 commands with docker exec. I am copying a file out of the docker container and don't want to have to deal with credentials to use something like ssh. This command copies a file:

sudo docker exec boring_hawking tar -cv /var/log/file.log | tar -x

But it creates a subdirectory var/log, I want to avoid that so if I could do these in the docker container I should be good:

cd /var/log ; tar -cv ./file.log

How can I make docker exec run 2 commands?

Docker Solutions


Solution 1 - Docker

This led to the answer: https://stackoverflow.com/questions/26274326/escape-character-in-docker-command-line I ended up doing this:

sudo docker exec boring_hawking bash -c 'cd /var/log ; tar -cv ./file.log' | tar -x

So it works by, sort of, running the one bash command with a parameter that is the 2 commands I want to run.

Solution 2 - Docker

Quite often, the need for several commands is to change the working directory — as in the OP's question.

For that, docker now has a -w option to specify the working directory. E.g. in the present case

docker exec -w /var/log boring_hawking tar -cv ./file.log

Solution 3 - Docker

For anyone else who stumbles across this and wants a different way to specify multiple commands in order to execute a more complex script:

cat <<EOF | docker exec --interactive boring_hawking sh
cd /var/log
tar -cv ./file.log
EOF

Solution 4 - Docker

If anyone else came here for the awesome answer, but also wants a better way to solve OP's original problem (OP's OP..?) to copy a file out of a docker container, there is now a docker cp command that will do this: https://docs.docker.com/engine/reference/commandline/cp/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSolxView Question on Stackoverflow
Solution 1 - DockerSolxView Answer on Stackoverflow
Solution 2 - DockerP-GnView Answer on Stackoverflow
Solution 3 - DockerzbrunsonView Answer on Stackoverflow
Solution 4 - DockerWill the ThrillView Answer on Stackoverflow