Here is a script I put together with some help from LLM's. Everything works except the last part of actually injecting the env file into my nodejs process.
FROM node:20.17-bullseye-slim AS dependencies
WORKDIR /usr/src/app/test
COPY package.json ./
RUN npm install --only=production
ARG APP_NAME
ENV APP_NAME=${APP_NAME}
RUN PKG_VERSION=$(node -p "require('./package.json').version") && echo "PKG_VERSION=\"$PKG_VERSION\"\nAPP_NAME=\"$APP_NAME\"" > docker.env
# Production image
FROM node:20.17-bullseye-slim AS runner
ENV NODE_ENV=production
WORKDIR /usr/src/app/test
# Copy dependencies and version.env from the previous stage
COPY --from=dependencies /usr/src/app/test/node_modules ./node_modules
COPY --from=dependencies /usr/src/app/test/docker.env ./
# Copy the rest of the app
COPY ./ ./
# Set permissions
RUN chown -R node:node .
USER node
RUN cat docker.env
# Load version into environment and start the app
CMD ["/bin/sh", "-c", ". ./docker.env && exec node main.js"]
I'm getting APP_NAME from my build-args and want to include version from my package file. Is this correct ?
The variables are lost when the . ./docker.env
command ends. To preserve them, export
the variables in your script by changing the command that creates the file to
RUN PKG_VERSION=$(node -p "require('./package.json').version") && echo "export PKG_VERSION=\"$PKG_VERSION\"\nexport APP_NAME=\"$APP_NAME\"" > docker.env