Search code examples
dockershellsh

Shell script on running a docker container


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 built an image using these:

docker build . -t test_build

and ran it 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 the 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?


Solution

  • 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