How to pass environment variables to a frontend web application?

后端 未结 5 1286
攒了一身酷
攒了一身酷 2020-12-07 16:15

I am trying to containerize a frontend web application and I am having troubles to figure out how to pass environment variables. The application is a Angular application, so

5条回答
  •  有刺的猬
    2020-12-07 16:37

    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.

提交回复
热议问题