node.jsdockernpmcontinuous-integrationnvm

Matching nvmrc node version to Docker node base image


I'm trying to streamline the development + build process for an older project where there's not been much management of the node version. For building the docker image which is used for both tests and deployment, I'd like to be able to pull the node version defined in .nvmrc file and pull the node base docker image using that.

Is there already a docker base image which achieves something like this, or is it a case of just writing it myself?


Solution

  • If you can control the command for docker, you can make use of docker build arguments in your base-image (https://docs.docker.com/engine/reference/builder/#understand-how-arg-and-from-interact)

    Create a docker file which looks like:

    ARG  NODE_VERSION
    FROM node:${NODE_VERSION}-alpine
    
    # Add your commands here
    

    Execute the following command:

    docker build --build-arg NODE_VERSION=$(cat .nvmrc | tr -cd [:digit:].)-f Dockerfile .
    

    The addition tr -cd [:digit:]. will remove any character you have in your .nvmrc file like line-breaks or the optional prefixed v.

    When using a multistage build (https://docs.docker.com/develop/develop-images/multistage-build/) - mostly used when you want the size of your final image to be as minimal as possible, your second image can also be based on build-args, but all build-args have to be declared before the first FROM statement, as far as I've tested it.

    Here's an example where I use this trick to to demeteorize my meteor application (transpiling it to an application which can be run using node) and copy those files on to a plain image which has the desired node version: https://github.com/disney/meteor-base/issues/30