DenCowboy DenCowboy - 1 month ago 14
Node.js Question

Can run npm / node in docker container but not in dockerfile

I have dockerfile which has base image go and I install npm/node:

FROM golang:1.7
RUN apt-get update && apt-get install -y wget

###node
ENV NVM_DIR /usr/local/nvm
ENV NODE_VERSION 6.10.1

RUN wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.3/install.sh | bash \
&& . $NVM_DIR/nvm.sh \
&& nvm install $NODE_VERSION \
&& nvm alias default $NODE_VERSION \
&& nvm use default

ENV NODE_PATH $NVM_DIR/v$NODE_VERSION/lib/node_modules
ENV PATH $NVM_DIR/v$NODE_VERSION/bin:$PATH


When I start this container I can perform
node
or
npm
commands inside the container:

docker exec -it 763993cc1f7a bash
root@763993cc1f7a:/go# npm -v
3.10.10


But when I add a node or npm command to the dockerfile:

RUN npm ...


I get:
/bin/sh: 1: npm: not found

How is this possible?

Answer Source

You need to avoid using NVM. You can do this using Multi stage dockerfile in your code. Assuming Go is the main app and npm is needed for webpack or other build activity

So you final docker file should be something like below

ARG NODE_VERSION
FROM node:${NODE_VERSION} as static
...
RUN webpack build


FROM go:1.7
COPY --from=static /app/static /app/static
....
CMD ["./goapp"]

This feature was introduce in Docker 17.05 ce, so you will need the latest version.