Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run 2 commands with docker exec

Tags:

docker

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?

like image 390
Solx Avatar asked Oct 29 '15 13:10

Solx


People also ask

How do I run multiple commands in Docker exec?

In order to execute multiple commands using the “docker exec” command, execute “docker exec” with the “bash” process and use the “-c” option to read the command as a string. Note: Simple quotes may not work in your host terminal, you will have to use double quotes to execute multiple commands.

Can Dockerfile run 2 commands?

There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified with the JSON array format.

What is the difference between docker run and Docker exec?

Docker Run vs Docker Exec! This is a fairly common question – but has a simple answer! In short, docker run is the command you use to create a new container from an image, whilst docker exec lets you run commands on an already running container! Easy!


2 Answers

This led to the answer: 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.

like image 136
Solx Avatar answered Oct 11 '22 01:10

Solx


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 
like image 29
P-Gn Avatar answered Oct 11 '22 01:10

P-Gn