How to pass environment variables to a frontend web application?

后端 未结 5 1301
攒了一身酷
攒了一身酷 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:26

    I had a similar problem for a static HTML file and here is what I wanted to solve:

    • the number of env vars can scale
    • the env vars can be set at launch time and not at build time
    • not worrying about maintaining the format of variable replacement so that it won't clash with other text

    I tried other answers but it seems like they didn't fit the above. So this is what I ended up with using envsubst

    Dockerfile

    FROM nginx:alpine
    COPY nginx.conf /etc/nginx/conf.d/default.conf
    COPY . /usr/share/nginx/html
    EXPOSE 80
    
    # awkwardly replace env variables
    COPY ./replaceEnvVars.sh /
    RUN chmod +x replaceEnvVars.sh
    ENTRYPOINT ["./replaceEnvVars.sh"]
    CMD ["nginx", "-g", "daemon off;"]
    

    replaceEnvVars.sh

    #!/bin/sh
    
    envsubst < /usr/share/nginx/html/index.tmpl.html > /usr/share/nginx/html/index.html && nginx -g 'daemon off;' || cat /usr/share/nginx/html/index.html
    

    index.tmpl.html

    
     ...
     
     ...
     Login
    
    

    docker-compose.yml

    version: '3'
    services:
      landing:
        build: .
        ...
        environment:
          - BASE_URL=https://dev.example.com
          - GA_CODE=UA-12345678-9
        ...
    

提交回复
热议问题