Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run bash function in Dockerfile

Tags:

bash

docker

I have a bash function nvm defined in /root/.profile. docker build failed to find that function when I call it in RUN step.

RUN apt-get install -y curl build-essential libssl-dev && \
    curl https://raw.githubusercontent.com/creationix/nvm/v0.16.1/install.sh | sh
RUN nvm install 0.12 && \
    nvm alias default 0.12 && \
    nvm use 0.12

The error is

Step 5 : RUN nvm install 0.12
 ---> Running in b639c2bf60c0
/bin/sh: nvm: command not found

I managed to call nvm by wrapping it with bash -ic, which will load /root/.profile.

RUN bash -ic "nvm install 0.12" && \
    bash -ic "nvm alias default 0.12" && \
    bash -ic "nvm use 0.12"

The above method works fine, but it has a warning

bash: cannot set terminal process group (1): Inappropriate ioctl for device
bash: no job control in this shell

And I want to know is there a easier and cleaner way to call the bash function directly as it's normal binary without the bash -ic wrapping? Maybe something like

RUN load_functions && \
    nvm install 0.12 && \
    nvm alias default 0.12 && \
    nvm use 0.12
like image 487
Quanlong Avatar asked Sep 22 '15 03:09

Quanlong


People also ask

Can you run a script in Dockerfile?

If you need to run a shell script in Dockerfile. If you're going to run bash scripts in a Docker container, ensure that you add the necessary arguments in the scripts. New Linux users find it a bit challenging to understand the instructions of Dockerfile.

How do I run a command in Dockerfile?

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile .

How do I run a shell script in Dockerfile ENTRYPOINT?

Step 1: Create a script.sh file and copy the following contents. Step 2: You should have the script.sh is the same folder where you have the Dockerfile. Create the Dockerfile with the following contents which copy the script to the container and runs it part of the ENTRYPOINT using the arguments from CMD.


1 Answers

Docker's RUN doesn't start the command in a shell. That's why shell functions and shell syntax (like cmd1 && cmd2) cannot being used out of the box. You need to call the shell explicitly:

RUN bash -c 'nvm install 0.12 && nvm alias default 0.12 && nvm use 0.12'

If you are afraid of that long command line, put those commands into a shell script and call the script with RUN:

script.sh

#!/bin/bash

nvm install 0.12 && \
nvm alias default 0.12 && \
nvm use 0.12

and make it executable:

chmod +x script.sh

In Dockerfile put:

RUN /path/to/script.sh
like image 176
hek2mgl Avatar answered Oct 20 '22 18:10

hek2mgl