【发布时间】:2020-11-26 08:09:39
【问题描述】:
我已经使用 Docker(和 Docker Compose)创建了一个 Vue 项目,并且正在使用 Dokku 进行部署。我已经对项目进行了足够的配置,可以在生产中成功部署。但是,我在尝试访问 Vue CLI 构建脚本中的环境变量时遇到了麻烦。由于 Vue CLI 的工作方式,环境变量本质上是在构建时(而不是运行时)内置到应用程序中的。这意味着我在编译应用程序时需要环境变量,我通过生产环境变量Dockerfile 进行管理。
Auth0 Dokku Guide 非常宝贵但在构建时(我被卡住了)没有处理将环境变量从 Dokku 传递到 Vue CLI。使用 Docker Compose(开发)这很容易,但 Dockerfile(生产)似乎有所不同(both ARG 和 ENV 用于所需的每个变量)。
# === Base stage =====
FROM node:12.2-alpine AS base
WORKDIR /app
# node_modules are managed inside the container
COPY package*.json ./
# === Dependency stage =====
FROM base AS dependencies
# Install ONLY production dependencies
RUN npm install --only=production
# Copy production dependencies aside
RUN cp -R node_modules prod_node_modules
# Install ALL dependencies
RUN npm install
# === Build stage =====
FROM dependencies AS build
# Copy the rest of the application
COPY . .
# NOTE: It appears to be necessary to use BOTH 'ARG' and 'ENV'?
ARG VUE_APP_API_URL
ENV VUE_APP_API_URL ${VUE_APP_API_URL}
# ...repeat for EVERY build variable necessary?
# Build the Vue application, outputting the static files to /dist
RUN npm run build
# === Release stage =====
FROM base AS release
# Copy production dependencies (overwriting all dependencies, used for building)
COPY --from=dependencies /app/prod_node_modules ./node_modules
# Copy the build artifacts from the build stage
COPY --from=build /app/dist ./dist
# Copy the simple server file
COPY server.js /app/server.js
EXPOSE 8080
CMD node server.js
关键部分是 ARG 和 ENV 的用法...没有比对 Vue 构建过程中使用的每个变量(即应用程序配置文件)重复此操作更好的方法吗?
# NOTE: It appears to be necessary to use BOTH 'ARG' and 'ENV'?
ARG VUE_APP_API_URL
ENV VUE_APP_API_URL ${VUE_APP_API_URL}
# ...repeat for EVERY build variable necessary?
应用成功构建并正确部署在小型 Express 服务器容器中。使用上述 Dockerfile 设置时,环境变量会在 Vue CLI 构建时填充。我在 Vue 项目中使用config.js 文件在构建时获取环境变量。注意VUE_APP_ 变量前缀的正确用法(Vue CLI 要求)。
export default {
api: {
url: process.env.VUE_APP_API_URL,
},
app: {
envName: process.env.VUE_APP_ENV_NAME || "local",
isProduction: process.env.NODE_ENV === "production",
},
};
我尝试将必要的环境变量添加为 Dokku config 变量和 docker-options 变量。我对构建时配置变量的Dokku docs 有点困惑。这是指仅在 Dockerfile 中使用的变量,还是本质上以 process.env 提供的变量?
# Set Dokku environment variables (NOT USED)
dokku config:set [app_name] VUE_APP_API_URL=https://api.example.org
# Set Docker build variable (USED WITH ARG/ENV)
dokku docker-options:add [app_name] build "--build-arg VUE_APP_API_URL=https://api.example.org"
必须有更好的方法来传递环境变量,而不是在 Dockerfile 中占用这么多行(和阶段)!
TL;DR: 在使用Dockerfile 构建时,有没有更好的方法将环境变量从 Dokku 传递到 Vue CLI 构建脚本?必须用这么多 ARG 和 ENV 声明来更新生产 Dockerfile 似乎很疯狂,然后仍然必须使用冗长的语法在 dokku docker-options 中单独设置每个声明!
TL;DR2: 为什么它不能与dokku config 一起使用,因为我没有使用构建时变量,但 Vue CLI 正在使用当前环境变量来构建应用程序?为什么 Vue CLI 在构建时使用 dokku config 变量?
【问题讨论】:
-
您好!我实际上面临与您完全相同的问题。只是想知道您是否设法找到了一个不错且干净的解决方案?
-
不幸的是,我没有这样做,但幸运的是应用程序需要的变量并不多(至少,现在......)。如果您找到更好的解决方案,请告诉我!
标签: docker vue.js environment-variables dokku