Dynamic configuration of environment variables

Categories

JavaScript Nginx Docker

How to Dynamically Modify Environment Variables with Vite and Nginx in Docker

When deploying a Vue.js/Vite application with Nginx in a Docker container, we face a challenge: the inability to modify environment variables once the application is built, as it becomes static. Here's an elegant solution to this problem.

1. Environment Variables Configuration

  • 1.1 Create a .env file at the root of your project. This file should be ignored by Docker by adding it to .dockerignore:
VITE_API_URL=http://localhost:8080
  • 1.2 Create a .env.production file that will link Vite variables with Docker environment variables:
VITE_API_URL=APP_API_URL

2. Variable Replacement Script

Create an env.sh file at the root that will dynamically replace variables when the container starts:

#!/bin/sh

# Loop through all environment variables starting with APP_
for i in $(env | grep APP_)
do
    key=$(echo $i | cut -d '=' -f 1)
    value=$(echo $i | cut -d '=' -f 2-)
    echo "Replacing ${key} with ${value}"

    # Replace occurrences in JS files
    find /usr/share/nginx/html -type f \( -name '*.js' \) -exec sed -i "s|${key}|${value}|g" '{}' +
done

3. Docker Configuration

Create a Dockerfile that will build the application and configure Nginx:

# Build stage
FROM node:22-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Production stage
FROM nginx:1.21.6-alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY /nginx.conf /etc/nginx/conf.d/default.conf
COPY env.sh /docker-entrypoint.d/env.sh
RUN chmod +x /docker-entrypoint.d/env.sh

4. Usage

  • 4.1 Building the Image
docker build -t app-front .
  • 4.2 Running the Container
docker run --rm -p 3000:80 -e APP_API_URL=http://localhost:8080 app-front

How Does It Work?

  1. During build, Vite replaces VITE_API_URL with the value APP_API_URL
  2. When the container starts, the env.sh script runs automatically
  3. The script searches for all environment variables starting with APP_
  4. It then replaces each occurrence of these variables in the JS files with their actual values

0 Comments