Home > Mobile >  Docker Angular: docker arguments doesn't work with ng build
Docker Angular: docker arguments doesn't work with ng build

Time:10-25

I have an argument called STAGE when building the docker image I provide this argument to docker build like so:

docker build --build-arg STAGE=test -t my-image:latest .

the STAGE value is the environment I want to use in my angular app but the build is not working as expected.
The Dockerfile:

FROM node:10.21.0
ARG STAGE
RUN npm install -g @angular/[email protected]

# install dependencies
WORKDIR /app
COPY package.json /app
COPY yarn.lock /app
RUN yarn add enhanced-resolve@^3.1.0
RUN yarn install --pure-lockfile

# build the frontend
COPY . /app
RUN ng build --configuration=$STAGE && cp favicon.png dist/

ENV ENVIRONMENT=$STAGE

# start the server
CMD node server.js

as you can see in the Dockerfile I build the Angular app using a specific environment, and I run a node server to serve the app, and at the same time I add an environment variable to the node container that contains the value of the STAGE argument in this line ENV ENVIRONMENT=$STAGE

The weird part is that the STAGE value sometimes contains a value and sometimes it's empty, how did I know that ?
I'm writing a console.log(environment) in both, Angular app and node server file
In Angular I get the default environment although the environment should be "test" and in node I get the correct value of the STAGE argument which is "test".
As a summary:
This line RUN ng build --configuration=$STAGE && cp favicon.png dist/ the STAGE value is empty
and in this line ENV ENVIRONMENT=$STAGE it contains a value!!

and also this happens only on AWS's CodeBuild when building the project, when I run the docker build locally it works fine!

Any thoughts on why this happens?

CodePudding user response:

I cannot replicate your issue, but you may try to substitute

ENV ENVIRONMENT=$STAGE

# start the server
CMD node server.js

with

CMD /bin/sh ENVIRONMENT=$STAGE node server.js

Please tell me if it works.

Edit

The instruction RUN ng build --configuration=$STAGE should get the value for $STAGE from environment, and not from docker build argument, so you rewrite you docker file as follow:

FROM node:10.21.0

ARG STAGE
ENV ENVIRONMENT=$STAGE

RUN npm install -g @angular/[email protected]

# install dependencies
WORKDIR /app
COPY package.json /app
COPY yarn.lock /app
RUN yarn add enhanced-resolve@^3.1.0
RUN yarn install --pure-lockfile

# build the frontend
COPY . /app
RUN ng build --configuration=$ENVIRONMENT && cp favicon.png dist/

# start the server
CMD node server.js

CodePudding user response:

You will need to move the ENV ENVIRONMENT=$STAGE right after you define your arg ARG STAGE

and point to $ENVIRONMENT in your ng build - ng build --configuration=$ENVIRONMENT

also make sure to supply the argument when building the image

docker build --build-arg STAGE=test .

  • Related