bra*_*fox 2 node.js docker vue.js docker-compose
Docker-compose 环境变量似乎根本没有设置。我曾尝试使用 env_file 和 environment 字段,但是在我的 vue 应用程序中打印 process.env 时,唯一可见的变量是 NODE_ENV 和 BASE_URL
这是我的 docker-compose 代码:
frontend:
container_name: "Frontend"
build:
context: .
dockerfile: frontend.dockerfile
env_file:
- ./frontend.env
environment:
VUE_APP_BACKEND_URL: "django"
ports:
- 8000:80
command: echo $VUE_APP_BACKEND_URL
Run Code Online (Sandbox Code Playgroud)
前端 Dockerfile:
# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY ./front/package*.json ./
RUN npm install
COPY ./front .
RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)
我的 frontend.env 代码(这是在我尝试调试问题时添加的):
VUE_APP_BACKEND_URL=django
VUE_APP_BACKEND_PORT=9000
Run Code Online (Sandbox Code Playgroud)
这是我的js代码
export function getEnvironmentVar(key,defaultVal){
window.console.log(process.env)
window.console.log(process.env.VUE_APP_BACKEND_URL)
var result = process.env[`VUE_APP_${key}`];
window.console.log(`Trying to read environment variable: ${key}, got: ${result}`)
if(result!= undefined)
return result
else
return defaultVal
}
Run Code Online (Sandbox Code Playgroud)
输出:
{NODE_ENV: "production", BASE_URL: "/"}
NODE_ENV: "production"
BASE_URL: "/"
__proto__: Object
Run Code Online (Sandbox Code Playgroud)
这是在 docker-compose 中添加命令行的输出:
WARNING: The VUE_APP_BACKEND_URL variable is not set. Defaulting to a blank string.
Starting Frontend ... done
Attaching to Frontend
Frontend |
Frontend exited with code 0
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您设置的环境变量应用于容器的运行时环境,而不是在构建时应用于容器。由于您的 Web 应用程序是静态构建和提供的,因此环境变量在前端将不可用,因为它们在构建应用程序时未设置。
为了使环境变量可见vue-cli,当它建立你的应用程序,你需要使用编译参数在你的Dockerfile。然后,您可以在运行npm run build.
前端.dockerfile
# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
ARG VUE_APP_BACKEND_URL # <-- these two lines have
ENV VUE_APP_BACKEND_URL=$VUE_APP_BACKEND_URL # been added
COPY ./front/package*.json ./
RUN npm install
COPY ./front .
RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)
docker-compose.yml
services:
frontend:
container_name: "Frontend"
build:
context: .
dockerfile: frontend.dockerfile
args:
- VUE_APP_BACKEND_URL=django
ports:
- 8000:80
Run Code Online (Sandbox Code Playgroud)
由于VUE_APP_BACKEND_URL在npm run build执行之前设置,环境变量将嵌入到您构建的应用程序中。
资料来源:
| 归档时间: |
|
| 查看次数: |
2640 次 |
| 最近记录: |