ptk
ptk

Reputation: 7653

Why can't I run command in Dockerfile but I can from within the my Docker container?

I have the following Dockerfile. This is what the "n" package is.

FROM ubuntu:18.04

SHELL ["/bin/bash", "-c"]

# Need to install curl, git, build-essential
RUN apt-get clean
RUN apt-get update
RUN apt-get install -y build-essential
RUN apt-get install -y curl
RUN apt-get install -y git

# Per docs, the following allows automated installation of n without installing node https://github.com/mklement0/n-install
RUN curl -L https://git.io/n-install | bash -s -- -y

# This refreshes the terminal to use "n"
RUN . /root/.bashrc

# Install node version 6.9.0
RUN /root/n/bin/n 6.9.0

This works perfectly and does everything I expect.

Unfortunately, after refreshing the terminal via RUN . /root/.bashrc, I can't seem to call "n" directly and instead I have to reference the exact binary using RUN /root/n/bin/n 6.9.0.

However, when I docker run -it container /bin/bash into the container and run the above sequence of commands, I am able to call "n" like so: Shell command: n 6.9.0 with no issues.

Why does the following command not work in the Dockerfile?

RUN n 6.9.0

I get the following error when I try to build my image:

/bin/bash: n: command not found

Upvotes: 0

Views: 1112

Answers (1)

David Maze
David Maze

Reputation: 159810

Each RUN command runs a separate shell and a separate container; any environment variables set in a RUN command are lost at the end of that RUN command. You must use the ENV command to permanently change environment variables like $PATH.

# Does nothing
RUN export FOO=bar
# Does nothing, if all the script does is set environment variables
RUN . ./vars.sh
# Needed to set variables
ENV FOO=bar

Since a Docker image generally only contains one prepackaged application and its runtime, you don't need version managers like this. Install the single version of the language runtime you need, or use a prepackaged image with it preinstalled.

# Easiest
FROM node:6.9.0
# The hard way
FROM ubuntu:18.04
ARG NODE_VERSION=6.9.0
ENV NODE_VERSION=NODE_VERSION
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --assume-yes --no-install-recommends \
      curl
RUN cd /usr/local \
 && curl -LO https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz \
 && tar xjf node-v${NODE_VERSION}-linux-x64.tar.xz \
 && rm node-v${NODE_VERSION}-linux-x64.tar.xz \
 && for f in node npm npx; do \
      ln -s ../node-v${NODE_VERSION}-linux-x64/bin/$f bin/$f; \
    done

Upvotes: 1

Related Questions