Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute commands in docker container as part of bash shell script

Tags:

bash

shell

docker

I would like to write a bash script that automates the following:

Get inside running container

docker exec -it CONTAINER_NAME /bin/bash

Execute some commands:

cat /dev/null > /usr/local/tomcat/logs/app.log
exit

The problematic part is when docker exec is executed. The new shell is created, but the other commands are not executed.

Is there a way to solve it?

like image 649
Patrik Mihalčin Avatar asked Apr 14 '16 15:04

Patrik Mihalčin


People also ask

How do I run a command in a docker container?

Running Commands in an Alternate Directory in a Docker Container. To run a command in a certain directory of your container, use the --workdir flag to specify the directory: docker exec --workdir /tmp container-name pwd.

How do I run a shell script inside a docker container?

Step 1: Create a script.sh file and copy the following contents. Step 2: You should have the script.sh is the same folder where you have the Dockerfile. Create the Dockerfile with the following contents which copy the script to the container and runs it part of the ENTRYPOINT using the arguments from CMD.

Can I run docker commands from Git bash?

Even though you run your docker executable in "git bash" the underlying executable is still a windows version of docker which makes it hiccup. On Powershell this works because Powershell creates the path as it should (windows version) on CMD the shell does not understand this command. and it might actually work.


1 Answers

You can use heredoc with docker exec command:

docker exec -i CONTAINER_NAME bash <<'EOF'
cat /dev/null > /usr/local/tomcat/logs/app.log
exit
EOF

To use variables:

logname='/usr/local/tomcat/logs/app.log'

then use as:

docker exec -i CONTAINER_NAME bash <<EOF
cat /dev/null > "$logname"
exit
EOF
like image 67
anubhava Avatar answered Sep 30 '22 23:09

anubhava