Vue3+ViteJS项目Docker Compose动态配置环境变量(无需.env文件)
无需.env文件的Vue3+Vite+Docker Compose动态配置方案
针对你遇到的Vite构建时无法读取Docker Compose环境变量的问题,以下是几个无需依赖.env文件的动态配置方案,适配不同场景需求:
方案1:Docker构建时传递构建参数
适合不同环境需要单独构建镜像的场景,直接在Docker构建阶段注入Vite所需的环境变量:
- 修改Dockerfile,添加构建参数接收逻辑:
# 定义构建参数 ARG VITE_API_URL ARG VITE_APP_TITLE # 将构建参数转为环境变量,供Vite读取 ENV VITE_API_URL=$VITE_API_URL ENV VITE_APP_TITLE=$VITE_APP_TITLE # 后续构建步骤(安装依赖、打包) WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build
- Vite配置文件中直接读取:
// vite.config.js import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], server: { proxy: { '/api': { target: process.env.VITE_API_URL, changeOrigin: true } } }, define: { // 若需在客户端直接使用,可通过define注入 '__APP_TITLE__': JSON.stringify(process.env.VITE_APP_TITLE) } })
- Docker Compose中传递构建参数:
services: vue-app: build: context: . args: VITE_API_URL: http://dev-api.example.com VITE_APP_TITLE: "开发环境" ports: - "5173:5173"
方案2:运行时注入静态配置文件
适合同一个镜像适配多环境的场景,在容器启动时动态替换前端配置:
- 创建公共配置模板:
在public目录下新建config.js作为模板:
window.APP_CONFIG = { apiUrl: '__API_URL__', appTitle: '__APP_TITLE__' }
- 编写启动脚本:
新建entrypoint.sh脚本,用于替换模板中的占位符:
#!/bin/sh # 替换配置文件中的占位符 sed -i "s/__API_URL__/$API_URL/g" /usr/share/nginx/html/config.js sed -i "s/__APP_TITLE__/$APP_TITLE/g" /usr/share/nginx/html/config.js # 启动服务(以Nginx为例,生产镜像常用) nginx -g 'daemon off;'
- 修改Dockerfile:
WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build # 复制静态文件和启动脚本到Nginx目录 COPY --from=build /app/dist /usr/share/nginx/html COPY public/config.js /usr/share/nginx/html/config.js COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"]
- Docker Compose中传递运行时变量:
services: vue-app: image: your-vue-image:latest environment: - API_URL=http://prod-api.example.com - APP_TITLE="生产环境" ports: - "80:80"
- Vue组件中使用配置:
<template> <h1>{{ appTitle }}</h1> </template> <script setup> const appTitle = window.APP_CONFIG.appTitle const apiUrl = window.APP_CONFIG.apiUrl </script>
方案3:开发环境直接传递环境变量
开发阶段Vite Dev Server是实时运行的,可直接读取容器内的环境变量:
- Docker Compose配置:
services: vue-dev: build: . environment: - VITE_API_URL=http://dev-api.local - VITE_APP_TITLE="开发预览" ports: - "5173:5173" volumes: - ./src:/app/src - ./public:/app/public
- Vite配置和组件中直接使用:
Vite会自动识别VITE_前缀的变量,可在客户端通过import.meta.env.VITE_API_URL直接访问,配置文件中则用process.env.VITE_API_URL读取。
内容的提问来源于stack exchange,提问作者ETorre
相关产品推荐
相关产品推荐

