How to build Angular app in docker container using process.env variables

I’m using a server to build an Angular App using a node.js image in docker-compose with an environment-file specified in the docker-compose.yaml.

Here’s the Dockerfile for the build:

FROM node:10.17

RUN wget -q -O - | apt-key add -
RUN sh -c 'echo "deb [arch=amd64] stable main" >> /etc/apt/sources.list.d/google.list'

RUN apt-get update

RUN apt install curl gnupg2 ca-certificates lsb-release -yq
RUN echo "deb `lsb_release -cs` nginx" | tee /etc/apt/sources.list.d/nginx.list
RUN curl -fsSL | apt-key add -
RUN apt-key fingerprint ABF5BD827BD9BF62

RUN apt-get update && apt-get install -yq google-chrome-stable
RUN apt install nginx


ENV PATH /app/node_modules/.bin:$PATH

COPY package.json /app/package.json
RUN npm install -g @angular/[email protected]
RUN npm install

COPY . /app


RUN ts-node set-env.ts

RUN ng build --prod --base-href

RUN rm /etc/nginx/conf.d/default.conf
COPY default.conf /etc/nginx/conf.d
RUN mv dist/docker-node/* /usr/share/nginx/html/


CMD ["nginx", "-g", "daemon off;"]

and here’s the script inside set-env.ts:

const fs = require('fs');
// Configure Angular `environment.ts` file path
const targetPath = './src/environments/';
// Load node modules
const colors = require('colors');
// `environment.ts` file structure
const envConfigFile = `export const environment = {
   production: true,
   TEST: '${process.env.TEST}'

fs.writeFile(targetPath, envConfigFile, function (err) {
   if (err) {
       throw console.error(err);

My problem is that when docker runs the command RUN ts-node set-env.ts the process.env.TEST is not there yet and the result is that TEST in my app is undefined. But if I run the command in the container after the build is complete, process.env.TEST is present and the file is correctly modified.

I think that the problem is that the environment variables are passed from docker to the container as soon as the container starts, while I’m trying to use those in the Dockerfile before the container has started. Is there a way to use the environment variables in the Dockerfile before the container starts?

Another solution would be starting the build of the angular application after the container has started but I don’t quite get how to add the build instruction in the CMD.

Source: StackOverflow