gpt4 book ai didi

node.js - Docker-compose变量未传递到生产vue应用中

转载 作者:行者123 更新时间:2023-12-02 20:33:22 25 4
gpt4 key购买 nike

Docker组成的环境变量似乎根本没有设置。我尝试使用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

前端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;"]

我的frontend.env代码(这是在我尝试调试问题时添加的):
VUE_APP_BACKEND_URL=django
VUE_APP_BACKEND_PORT=9000

这是我的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
}

输出:
{NODE_ENV: "production", BASE_URL: "/"}
NODE_ENV: "production"
BASE_URL: "/"
__proto__: Object

这是在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

我究竟做错了什么?

最佳答案

您正在设置的环境变量将应用于容器的运行时环境,而不是在构建时应用于容器。由于您的Web应用程序是静态生成和提供的,因此环境变量在前端将不可用,因为在构建应用程序时未设置它们。

为了使vue-cli在构建应用程序时环境变量可见,您需要在Dockerfile中使用build参数。然后,您可以在运行npm run build之前,在构建阶段使用与build参数相同的值设置环境变量。

frontend.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;"]

docker-compose.yml
services:
frontend:
container_name: "Frontend"
build:
context: .
dockerfile: frontend.dockerfile
args:
- VUE_APP_BACKEND_URL=django
ports:
- 8000:80

由于在执行 VUE_APP_BACKEND_URL之前已设置 npm run build,因此环境变量将嵌入在您构建的应用程序中。

来源:
  • StackOverflow-Pass environment variables from docker-compose to container at build stage
  • 撰写文件引用-https://docs.docker.com/compose/compose-file/#build
  • 关于node.js - Docker-compose变量未传递到生产vue应用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60474384/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com