1

I have a Dockerfile where I am copying in a shell script called myscript.sh that I want to run each time a container made from the image starts. The script copies in fine but will not execute when the container starts. Once the container starts, I can interactively connect and manually run the script with no issues but it won't run at start.

Contents of myscript.sh:

#!/bin/bash

mkdir -p /root/newfolder

Dockerfile:

FROM ubuntu:20.04

COPY ./src* /src
COPY ./myscript.sh /usr/local/bin

CMD ["/usr/local/bin/myscript.sh"]

I have also tried:

CMD ["/bin/bash", "/usr/local/bin/myscript.sh"]

When I run docker run -it -d --name {container_name} {image_name} bash it creates a container from the image and gives me shell prompt. I check to see if the script created the folder but it does not. If I then interactively run the script, the folder is created with no issues.

I have looked at other solutions and none seem to work. What am I missing?

phydeauxman
  • 1,432
  • 3
  • 26
  • 48

1 Answers1

0

The way you invoke your docker run command means that you have overriden the default CMD specified in your image

$ docker run --help                                                                             
                                                                                                
Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]    

You can see in the syntax you use that bash is supplied for the optional [COMMAND] argument. If you omit this argument, you should see that your command does run in the container.

However, if you want to drop into an interactive shell in the container afterwards, then you should replace the CMD instruction with a RUN instruction and then pass bash as the command.

Micah Smith
  • 4,203
  • 22
  • 28
  • your guidance was accurate in producing the behavior I am looking for but I need the shell script to run when an instance is created from the image and it appears that using the RUN verb in the Dockerfile causes it to run when the image is created. I am trying to create an image that will be used in multiple different environments and script needs to run in the target environment. – phydeauxman May 28 '21 at 16:07