React使用docker传环境变量

  1. Dockerfile文件内容
    # => Build container
    FROM node:alpine as builder
    
    WORKDIR /app
    COPY app/package.json .
    COPY app/yarn.lock .
    RUN yarn config set registry https://registry.npm.taobao.org -g
    RUN yarn config set sass_binary_site http://cdn.npm.taobao.org/dist/node-sass -g
    RUN yarn
    COPY app/. .
    RUN yarn build
    
    # => Run container
    FROM nginx:1.15.2-alpine
    
    # Nginx config
    RUN rm -rf /etc/nginx/conf.d
    COPY conf /etc/nginx
    
    # Static build
    COPY --from=builder /app/build /usr/share/nginx/html/
    
    # Default port exposure
    EXPOSE 80
    
    # Copy .env file and shell script to container
    WORKDIR /usr/share/nginx/html
    COPY ./env.sh .
    COPY .env .
    
    # Add bash
    RUN echo http://mirrors.aliyun.com/alpine/v3.7/main/ >> /etc/apk/repositories
    RUN apk add --no-cache bash
    
    # Make our shell script executable
    RUN chmod +x env.sh
    
    # Start Nginx server
    CMD ["/bin/bash", "-c", "/usr/share/nginx/html/env.sh && nginx -g \"daemon off;\""]
    
    # CMD ["/bin/bash", "-c", "nginx -g \"daemon off;\""]
    

     

  2. .env文件内容

    api_url=http://localhost:8001/

     

  3. env.sh文件内容

    #!/bin/bash
    
    # Recreate config file
    rm -rf ./env-config.js
    touch ./env-config.js
    
    # Add assignment 
    echo "window._env_ = {" >> ./env-config.js
    
    # Read each line in .env file
    # Each line represents key=value pairs
    while read -r line || [[ -n "$line" ]];
    do
      # Split env variables by character `=`
      if printf '%s\n' "$line" | grep -q -e '='; then
        varname=$(printf '%s\n' "$line" | sed -e 's/=.*//')
        varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//')
      fi
    
      # Read value of current variable if exists as Environment variable
      value=$(printf '%s\n' "${!varname}")
      # Otherwise use value from .env file
      [[ -z $value ]] && value=${varvalue}
      
      # Append configuration property to JS file
      echo "  $varname: \"$value\"," >> ./env-config.js
    done < .env
    
    echo "}" >> ./env-config.js
    

     

  4. 接收参数

    window._env_ = window._env_ || {};
    // window._env_.api_url = '';

     

  5. docker build命令

    sudo docker build --no-cache --memory-swap -1 . -t 镜像名称

     

  6. docker 启动命令 

    sudo docker run -p 3000:80 -e api_url=http://0.0.0.0:8001/ -d -t 镜像名称

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值