This is how my Dockerfile looks like: First I copy the files, then I run npm install
and npm build
. As you can see, I do set the productive ENV variable.
I would like to get the version of the current package.json file to the running docker image. So I thought of using en ENV variable, e.g. VERSION
.
My package.json file could look like this:
"version": "0.0.1"
"scripts": {
"version": "echo $npm_package_version"
}
So npm run version
returns the version value. But I don't know how to use this result as ENV in my dockerfile
COPY . /app
RUN npm install --silent
RUN npm run build
RUN VERSION=$(npm run version)
ENV NODE_ENV production
ENV VERSION ???
CMD ["node", "server.js"]
If you just need the version from inside of your node app.. require('./package.json').version
will do the trick.
Otherwise, since you're already building your own container, why not make it easier on yourself and install jq? Then you can run VERSION=$(jq .version package.json -r)
.
Either way though, you cannot simply export a variable from a RUN command for use in another stage. There is a common workaround though:
FROM node:8-alpine
RUN apk update && apk add jq
COPY package.json .
COPY server.js .
RUN jq .version package.json -r > /root/version.txt
CMD VERSION=$(cat /root/version.txt) node server.js
Results from docker build & run:
{ NODE_VERSION: '8.11.1',
YARN_VERSION: '1.5.1',
HOSTNAME: 'xxxxx',
SHLVL: '1',
HOME: '/root',
VERSION: '1.0.0',
PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
PWD: '/' }