Creating output file through Shell Script running from Docker Container

Hello,

I am trying to capture the output of a command in a shell script to a log file. (This is the actual requirement in a complex shell script.). The shell script shall run within a Docker Container.

Below are the entries my Dockerfile to create the Docker Image

From ubuntu
COPY . .
CMD ["sh","shelljob.sh"]

Below is the content of the shelljob.sh

#!/bin/sh
usr=`whoami`
mc=`hostname`
dt=`date`
pt=`pwd`

touch dockshell.log
echo "$dt - I am $usr@$mc running from $pt printed by Shell Script" >> dockshell.log

I have used the below Docker commands on my MacBook

docker build -t myapp .
docker run myapp ----> This ran without any error

docker run -it myapp bash
root@33ee7a7451e6:/# ls dockshell.log
ls: cannot access 'dockshell.log': No such file or directory
root@33ee7a7451e6:/#

I am new to Docker world. Will you please guide me about where did I do the mistake and why it is not creating the outputfile inside the container?

By specifíing bash as the last argument you overwrote the original command so it won’t run. If you want to learn about commands in containers, I recommend reading my blogpost which shows lots of examples as well

In short, you could use an entrypoint which runs the commands before executing bash or any specified argument of docker run. It looks like I didn’t mention it in the blogpost, but I had examples in other projects like this

The difference is that you need something like this:

FROM ubuntu
COPY . .
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

Where entrypoint.sh is

shelljob.sh
exec "$@"

$@ means all the arguments of the entrypoint which is exactly what CMD defines and the last arguments of docker run define.