I’m having issues getting env vars in my Vite/Vue applications. Is it normal that I need to copy over my .env
file in my container? Or am I doing something wrong?
My Vue application is located inside my frontend
folder. This is my Dockerfile:
# Stage 1: Build the Vue application
FROM node:18 AS builder
# Set the working directory
WORKDIR /app
# Copy the package.json and package-lock.json files from the frontend folder
COPY frontend/package*.json ./
# Install the dependencies
RUN npm install --loglevel verbose
# Copy the rest of the application files from the frontend folder
COPY frontend/ .
# Copy the .env file for local development
COPY .env ./
# Build the application using the specified config
RUN npx vite build --config vite.config.js
# Stage 2: Serve the application with Nginx
FROM nginx:alpine as frontend-prod
# Copy the built files from the previous stage
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy the Nginx configuration file from the frontend folder
COPY frontend/nginx.conf /etc/nginx/nginx.conf
# Expose port 80
EXPOSE 80
# Start Nginx server
CMD ["nginx", "-g", "daemon off;"]
This is my vite.config.js
:
// Plugins
import Vue from '@vitejs/plugin-vue'
import ViteFonts from 'unplugin-fonts/vite'
import Components from 'unplugin-vue-components/vite'
import Vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
// Utilities
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
// Log statement to ensure the config file is being executed
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
// Determine the root path
const env = loadEnv(mode, process.cwd())
return {
base: '/',
plugins: [
Vue({
template: { transformAssetUrls }
}),
// https://github.com/vuetifyjs/vuetify-loader/tree/master/packages/vite-plugin#readme
Vuetify(),
Components(),
ViteFonts({
google: {
families: [{
name: 'Roboto',
styles: 'wght@100;300;400;500;700;900',
}],
},
custom: {
families: [
{
name: 'MaterialDesignIcons',
local: 'MaterialDesignIcons',
src: './src/assets/materialdesignicons-webfont.woff2',
},
],
preload: true,
}
}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
extensions: [
'.js',
'.json',
'.jsx',
'.mjs',
'.ts',
'.tsx',
'.vue',
],
},
server: {
port: 3000,
},
define: {
'process.env': env
}
}
})
If I do not include this .env
copy, my env vars are not taken into account. Is it due to the fact that my vite.config.js
is in the frontend folder?
├── Dockerfile.frontend
├── .env
├── frontend
│ ├── 404.html
│ ├── README.md
│ ├── dist
│ ├── eslint.config.mjs
│ ├── index.html
│ ├── jsconfig.json
│ ├── nginx.conf
│ ├── node_modules
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ ├── src
│ └── vite.config.js