Home > Enterprise >  Shell script on running a docker container
Shell script on running a docker container

Time:05-29

I created a Dockerfile like below:

From alpine:latest

WORKDIR /
COPY ./init.sh .
CMD ["/bin/sh", "./init.sh"]

and a script file init.sh like below:

#!/bin/sh

mkdir -p mount_point
echo hello > ./mount_point/hello.txt

and I build an image using these as:

docker build . -t test_build

and run as

docker container run --rm --name test_run -it test_build sh

where there are only two above files in the folder ().

In the container, I can find the init.sh file with x(executable) as is in the host.

However, there is no folder mount_point which should be created by

CMD ["bin/sh", "./init.sh"]

Note that, when I run any of below in the container, it successfully creates mount_point as I expected

sh init.sh

or

/bin/sh init.sh

and

sh -c ./init.sh

Could you tell me where I made mistakes ?

CodePudding user response:

When you do

docker container run --rm --name test_run -it test_build sh

the sh at the end overrides the CMD definition in the image and the CMD isn't run.

To verify that your script works, your can change the script to something like this

#!/bin/sh
echo Hello from the script!
mkdir -p mount_point
echo hello > ./mount_point/hello.txt
ls -al ./mount_point

Then run the image without the sh and you should see the 'Hello' message and the directory listing from the ./mount_point directory.

docker container run --rm --name test_run test_build
  • Related