前后端分离,如何在前端项目中动态插入后端API基地址?(in docker)
尴尬从何而来
# ------------------------------------------------------
# generate chunk files
# ------------------------------------------------------
FROM node:10-alpine as builder
# install and cache app dependencies
COPY package.json package-lock.json ./
RUN npm install && mkdir /react-frontend && mv ./node_modules ./react-frontend
WORKDIR /react-frontend
COPY . .
RUN npm run build
# ------------------------------------------------------
# Production Build
# ------------------------------------------------------
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /react-frontend/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
“或许你会针对不用的后端环境(canary、staging、production)构建不同的前端镜像,但这是一次又一次的工作量,并不是最佳实践。
前端独立部署,动态插入后端API基地址(in Docker)
前端项目插入配置的脚本如下:
// FILE: set-env.ts
...
export const environment = {
production: ${isProd},
apiBaseUrl: 'API_BASE_URL',
version: 'v${require('../package.json').version}'
};
...
我们在前端配置中写入API_BASE_URL
占位符,按照既定流程前端打包;
Dockerfile CMD指令指示容器如何运行:
-
用真实值替换前端chunk files中原插入的 API_BASE_URL
占位符 -
使用nginx承载替换后的chunk files
# FILE: Dockerfile
...
EXPOSE 80
COPY --from=builder /react-frontend/replace_api_url.sh /
CMD ["sh", "replace_api_url.sh"]
下面是replace_api_url.sh的内容:
#!/usr/bin/env sh
find '/usr/share/nginx/html' -name '*.js' -exec sed -i -e 's,API_BASE_URL,'"$API_BASE_URL"',g' {} \;
nginx -g "daemon off;"
正常构建镜像之后;现在生成容器时,可通过环境变量传参替换原前端chunk files的API_BASE_URL字符串
docker build -t front .
docker run -p 80:80 -e API_BASE_URL=http://somebackend.com/api front