I have the same docker image with my vuejs (with vite) deployed in 3 different environment (stage, qa and prod) with kubernetes, in this 3 environment i have the same environment variable with 3 differents values, for exemple: in stage i have VITE_APP_URL=test1, in qa i have VITE_APP_URL=test2 and in prod i have VITE_APP_URL=test3. In my code i have this lines to retrieve the value: import.meta.env.VITE_APP_URL
but when i go check the variable it return nothing.. I would like to know if there is a way to retrieve the environment variable on my front which is on the server.
This is my Dockerfile if it can help:
FROM node:20.10 as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# étape de production
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Option 1
The environment variable is hard coded into the Dockerfile
. This does not seem ideal. See Option 2 below.
FROM node:20.10 as build-stage
ENV VITE_APP_URL=test2
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Option 2
Have a collection of environment files, the appropriate one chosen at build time.
For example:
🗎 .env-staging
VITE_APP_URL=test1
🗎 .env-qa
VITE_APP_URL=test2
🗎 .env-prod
VITE_APP_URL=test3
Modify Dockerfile
as follows:
FROM node:20.10 as build-stage
ARG ENV_FILE
ENV ENV_FILE=${ENV_FILE}
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN cp ${ENV_FILE} .env && \
npm run build
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Now you specify the appropriate environment file as a build argument, using whichever of the following is appropriate.
docker build --build-arg ENV_FILE=.env-staging -t vite-app .
docker build --build-arg ENV_FILE=.env-qa -t vite-app .
docker build --build-arg ENV_FILE=.env-prod -t vite-app .