Search code examples
reactjsdockerenvironment-variablesvite

Docker with Vite - env variables are undefined inside the docker container


I'm building a react project with Vite, and I'm new to Docker, and when I created a docker file, all was good, but the env variables are always undefined inside the Docker container.

Here's my simple Dockerfile ...

FROM node:18.17.1-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build
EXPOSE 8080
CMD ["npm","run","preview"]

And here's the .dockerignore file ...

README.md
build
dist
node_modules
LICENSE
package-lock.json
.git
.DS_Store
.env

And here's the .env file ...

VITE_API_BASE_URL=https://example.com

And this is how I'm accessing the env variable inside the code ...

import.meta.env.VITE_API_BASE_URL

Whenever I build the Docker image and run the Docker container, the VITE_API_BASE_URL is always undefined in the network tab, however when I remove the .env from the .dockerignore file and build the image again and run it, it works fine. But obviously that's not the solution, I need the app to be able to read the env variables inside the Dockere container.

What can I do?


Solution

  • For those who are struggling, and thanks to @jonrsharpe comment, here's what you need to do ...

    You need to pass the Env variables to your Docker container somehow, what worked for me was passing the variables during the Docker image build, NOT when running the container, by creating a build args in your Dockerfile like this ...

    FROM node:18.17.1-alpine
    
    # Define build arguments for environment variables
    ARG VITE_API_BASE_URL
    ARG VITE_API_KEY
    
    # Set environment variables during the build process
    ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
    ENV VITE_API_KEY=$VITE_API_KEY
    
    WORKDIR /app
    
    COPY package.json .
    RUN npm install
    COPY . .
    
    # Rest of your Dockerfile...
    
    # For example:
    RUN npm run build
    
    EXPOSE 8080
    CMD ["npm", "run", "preview"]
    

    Then you can pass the values of those args to your Docker image build command like this ...

    docker build \
      --build-arg VITE_API_BASE_URL=https://example.com \
      --build-arg VITE_API_KEY=A12O6f90eCfMFf8 \
      -t your-image-name .
    

    That's it.