dockerenvironment-variablesyarnpkg-v2

My dockers ENV YARN_VERSION does not match the actual version


Inside my docker container, the environment variable for my yarn version seems to be completely off. I am using Yarn 2, configured in the package.json. It works well, but I was confused when I stumbled over the ENV value.

What is the reason and might it have any side-effects?

package.json

{
  "name": "my-project",
  "type": "module",
  "scripts": {
    "watch": "node --watch src/app.js",
    "start": "node src/app.js",
  },
  "packageManager": "yarn@4.0.2"
}

Dockerfile:

FROM node:21.6-alpine3.19
ENV NODE_ENV=production
RUN corepack enable
USER node
WORKDIR /home/node/app
COPY --chown=node:node . .
RUN yarn install --immutable
CMD ["yarn", "start"]

checking the actual version:

~/app $ yarn -v
4.0.2

checking the env:

~/app $ echo $YARN_VERSION
1.22.19

Solution

  • The reason for this discrepancy is that the YARN_VERSION environment variable is defined in the base image.

    $ docker run -it node:21.6-alpine3.19 /bin/sh
    / # yarn -v
    1.22.19
    / # echo $YARN_VERSION
    1.22.19
    

    In your derived image you install another version of yarn. If you want then environment variable to be consistent then you can update it.

    ├── Dockerfile
    ├── entrypoint.sh
    ├── package.json
    └── src
        └── app.js
    

    🗎 Dockerfile

    FROM node:21.6-alpine3.19
    
    ENV NODE_ENV=production
    RUN corepack enable
    
    WORKDIR /app
    
    COPY . .
    
    RUN yarn install && \
        chmod +x ./entrypoint.sh
    
    ENTRYPOINT ["./entrypoint.sh"]
    
    CMD ["yarn", "start"]
    

    🗎 entrypoint.sh which will update YARN_VERSION.

    #!/bin/sh
    
    export YARN_VERSION=$(yarn -v)
    exec "$@"
    

    🗎 package.json as supplied in original question.

    🗎 src/app.js a little script with a greeting and the value of YARN_VERSION.

    console.log("Hello, World! from Yarn "+process.env.YARN_VERSION);
    

    enter image description here