How do I send RUN's output to ENV in Dockerfile?

I have the following code in my Dockerfile:

RUN NODE_VERSION=$( \
  curl -sL https://nodejs.org/dist/latest/ | \
  tac | \
  tac | \
  grep -oPa -m 1 '(?<=node-v)(.*?)(?=-linux-x64\.tar\.xz)' | \
  head -1 \
) \
&& echo $NODE_VERSION \
&& export NODE_VERSION="$NODE_VERSION"

ENV NODE_VERSION ${NODE_VERSION}

RUN echo "Node.js version found: $NODE_VERSION"

echo $NODE_VERSION returning 6.2.2 as it should, however export, ENV and RUN echo "Node.js version found: $NODE_VERSION" got empty output.

Is there a way to share one RUN command’s variable output to another commands in the Dockerfile, including ENV?

No. Each RUN command spawns its own shell, and that shell’s environment disappears when the shell exits.

If you need to have this information available at runtime, you could cat it to a file and then use an entrypoint script to set it again when the container starts up.

If you need to have this information available externally, the two approaches I’ve used are (a) create a file with a well-known name like /etc/container-version and put this data there (and depend on docker run to get it out again), or (b) use a shell script to find this data before you run docker build, and either generate the Dockerfile or (in more recent Dockers) pass it as an ARG.

1 Like

Thank You!

My final solution was to put the node.js archive download under the same command:

RUN NODE_VERSION=$( \
        curl -sL https://nodejs.org/dist/latest/ | \
        tac | \
        tac | \
        grep -oPa -m 1 '(?<=node-v)(.*?)(?=-linux-x64\.tar\.xz)' | \
        head -1 \
    ) \
    && echo $NODE_VERSION \
    && curl -SLO "https://nodejs.org/dist/latest/node-v$NODE_VERSION-linux-x64.tar.xz" -o "node-v$NODE_VERSION-linux-x64.tar.xz" \
    && curl -SLO "https://nodejs.org/dist/latest/SHASUMS256.txt.asc" \
    && gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \
    && grep " node-v$NODE_VERSION-linux-x64.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
    && tar -xJf "node-v$NODE_VERSION-linux-x64.tar.xz" -C /usr/local --strip-components=1 \
    && rm "node-v$NODE_VERSION-linux-x64.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt

THANK YOU dmaze.

To others out there, there is currently (2018-06) no way to get a value created during a RUN command into an ENV command. Nor can you run backtick commands as a value on an ENV command.

If its a value you want at runtime, just make it an environment variable in your entrypoint (aka runtime).