I’m trying to get the version while building the image by passing "–build-arg VERSION=" but the page shows the default version:
the application version is to be specified in the docker build… command. by giving value
the VERSION variable defined by the ARG instructions
# Stage 1: Build the application
FROM node:alpine AS builder
# Set the argument for the application version
ARG VERSION
# Install tools and dependencies
RUN apk add --update curl &&
rm -rf /var/cache/apk/*
# Set the working directory
WORKDIR /usr/app
# Copy application files
COPY ./package.json ./
# Install dependencies
RUN npm install
# Copy application files
COPY ./index.js ./
# Stage 2: Final image
FROM alpine
# Copy files from the build stage
COPY --from=builder /usr/app .
# Set the working directory
WORKDIR /usr/app
# Install Node.js
RUN apk --no-cache add nodejs npm
# Install Express.js
RUN npm install express
# Information about the internal container port on which the application listens
EXPOSE 8080
# Default command to start the container
CMD ["node", "index.js"]
# Set the environment variable for the application version
ENV VERSION=production.${VERSION:-v1.0}
const express = require('express');
const os = require('os');
const app = express();
const port = 8080;
app.get('/', (req, res) => {
let response = `Server IP Address: ${getIPAddress()}n`;
response += `Server Name (hostname): ${os.hostname()}n`;
response += `Application Version: ${process.env.VERSION}n`;
res.send(response);
});
app.listen(port, () => {
console.log(`The application is available on port ${port}`);
});
function getIPAddress() {
const interfaces = os.networkInterfaces();
for (const dev in interfaces) {
const iface = interfaces[dev].filter(details => details.family === 'IPv4' && !details.internal);
if (iface.length > 0) return iface[0].address;
}
return '0.0.0.0';
}
I use commend like this:
docker build –build-arg VERSION=2.0.0 -f Dockerfile10 -t local/base:v10 .
then:
docker run -d -p 8090:8080 –name web10 local/base:v10
result after command curl http://localhost:8090 -> it shows ip address, hostname but version is production.v1.0 instead of 2.0.0 as passed in –build-arg
2
Answers
There are two issues here:
ENV
needs to go beforeCMD
andARG
needs to go in the same stage as theENV
.Try something like this:
I agree with one of the comments on your question: it doesn’t look like you really need a multi-stage build because your
builder
stage is not really doing anything that’s not being done in the final stage.However, the
Dockerfile
above will at least work.It seems like there might be an issue with how you’re passing the VERSION build argument to the Docker build process and then accessing it within your Node.js application.
Docker Build Argument: You’re correctly passing the VERSION argument during the Docker build process
Rebuild Image
Run Container
Check Output