Run a script in Dockerfile

2019-01-30 14:41发布

I'm trying to run a script during my building process in my Dockerfile. But it doesn't seems to work.

I tried that way:

FROM php:7-fpm
ADD bootstrap.sh /
ENTRYPOINT ["/bin/bash", "/bootstrap.sh"]

Also this way:

FROM php:7-fpm    
ADD bootstrap.sh /
RUN bash -c "/bootstrap.sh"

And also bu executing my running container:

docker exec symfony /bin/bash -c "/bootstrap.sh"

Nothing seems to work.

Do you know how to do it?

3条回答
劳资没心,怎么记你
2楼-- · 2019-01-30 14:57

In addition to the answers above:

If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.

Tips:

  • If you use Notepad++, you need to click "Edit/EOL Conversion/UNIX (LF)"
  • If you use Visual Studio, I would suggest installing "End Of Line" plugin. Then you can make line endings visible by pressing Ctrl-R, Ctrl-W. And to set Linux style endings you can press Ctrl-R, Ctrl-L. For Windows style, press Ctrl-R, Ctrl-C.
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-30 15:04

Try to create script with ADD command and specification of working directory Like this("script" is the name of script and /root/script.sh is where you want it in the container, it can be different path:

ADD script.sh /root/script.sh

In this case ADD has to come before CMD, if you have one BTW it's cool way to import scripts to any location in container from host machine

In CMD place [./script]

It should automatically execute your script

You can also specify WORKDIR as /root, then you'l be automatically placed in root, upon starting a container

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-30 15:09

RUN and ENTRYPOINT are two different way to execute a script.

RUN means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.

ENTRYPOINT means your image (which has not executed the script yet) will create a container, and runs that script.

In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh is a good idea.

It should also start with a shebang (like #!/bin/sh)

Considering your script (KevinRaimbaud/docker-symfony/docker/php/bootstarp.sh: a couple of git config --global commands), it would be best to RUN that script once in your Dockerfile, but making sure to use the right user (the global git config file is %HOME%/.gitconfig, which by default is the /root one)

Add to your Dockerfile:

RUN /bootstart.sh

Then, when running a container, check the content of /root/.gitconfig to confirm the script was run.

查看更多
登录 后发表回答