How to pass environment variables to a frontend web application?

The way that I resolved this is as follows:

1.Set the value in the enviroment.prod.ts with a unique and identificable String:

export const environment = {
  production: true,
  REST_API_URL: 'REST_API_URL_REPLACE',
};

2.Create a entryPoint.sh, this entryPoint will be executed every time that you done a docker run of the container.

#!/bin/bash
set -xe
: "${REST_API_URL_REPLACE?Need an api url}"

sed -i "s/REST_API_URL_REPLACE/$REST_API_URL_REPLACE/g" /usr/share/nginx/html/main*bundle.js

exec "$@"

As you can see, this entrypoint get the ‘REST_API_URL_REPLACE’ argument and replace it (in this case) in the main*bundle.js file for the value of the var.

3.Add the entrypoint.sh in the dockerfile before the CMD (it need execution permissions):

FROM node:alpine as builder
COPY package.json ./
RUN npm i && mkdir /app && cp -R ./node_modules ./app
WORKDIR /app
COPY . .
RUN $(npm bin)/ng build --prod

FROM nginx:alpine
COPY nginx/default.conf /etc/nginx/conf.d/
RUN rm -rf /usr/share/nginx/html/*
COPY --from=builder /app/dist /usr/share/nginx/html

# Copy the EntryPoint
COPY ./entryPoint.sh /
RUN chmod +x entryPoint.sh

ENTRYPOINT ["/entryPoint.sh"]
CMD ["nginx", "-g", "daemon off;"]

4.Lauch the image with the env or use docker-compose (the slash must be escaped):

docker run -e REST_API_URL_REPLACE='http:\/\/backend:8080\/api'-p 80:80 image:tag

Probably exists a better solution that not need to use a regular expresion in the minified file, but this works fine.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)