{"id":456,"hash":"a17ef041062a77a3a7fb5a0b1f3b095eee89063ac6f2529d89456fff4580c951","pattern":"Docker with Vite - env variables are undefined inside the docker container","full_message":"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.\n\nHere's my simple Dockerfile ...\n\nFROM node:18.17.1-alpine\nWORKDIR /app\nCOPY package.json .\nRUN npm install\nCOPY . .\nRUN npm run build\nEXPOSE 8080\nCMD [\"npm\",\"run\",\"preview\"]\n\nAnd here's the .dockerignore file ...\n\nREADME.md\nbuild\ndist\nnode_modules\nLICENSE\npackage-lock.json\n.git\n.DS_Store\n.env\n\nAnd here's the .env file ...\n\nVITE_API_BASE_URL=https://example.com\n\nAnd this is how I'm accessing the env variable inside the code ...\n\nimport.meta.env.VITE_API_BASE_URL\n\nWhenever 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.\nBut obviously that's not the solution, I need the app to be able to read the env variables inside the Dockere container.\n\nWhat can I do?","ecosystem":"npm","package_name":"reactjs","package_version":null,"solution":"For those who are struggling, and thanks to @jonrsharpe comment, here's what you need to do ...\n\nYou 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 ...\n\nFROM node:18.17.1-alpine\n\n# Define build arguments for environment variables\nARG VITE_API_BASE_URL\nARG VITE_API_KEY\n\n# Set environment variables during the build process\nENV VITE_API_BASE_URL=$VITE_API_BASE_URL\nENV VITE_API_KEY=$VITE_API_KEY\n\nWORKDIR /app\n\nCOPY package.json .\nRUN npm install\nCOPY . .\n\n# Rest of your Dockerfile...\n\n# For example:\nRUN npm run build\n\nEXPOSE 8080\nCMD [\"npm\", \"run\", \"preview\"]\n\nThen you can pass the values of those args to your Docker image build command like this ...\n\ndocker build \\\n  --build-arg VITE_API_BASE_URL=https://example.com \\\n  --build-arg VITE_API_KEY=A12O6f90eCfMFf8 \\\n  -t your-image-name .\n\nThat's it.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/77486735/docker-with-vite-env-variables-are-undefined-inside-the-docker-container","votes":25,"created_at":"2026-04-19T04:51:09.966981+00:00","updated_at":"2026-04-19T04:51:09.966981+00:00"}