I have tried multiple options for the docker-compose to setup env variables for the react dockerfile – container but it’s not working
docker-compose.yaml
services:
weatherapi:
image: weatherapi_comp:1.0.1
container_name: weatherapi_comp_container
build:
context: ./WeatherDemo
dockerfile: Dockerfile
ports:
- "8901:8080"
command: ["dotnet", "WeatherDemo.dll"]
react-demoapp:
image: reactdemo_comp:1.0.1
container_name: reactdemo_comp_container
env_file: myconfig.env
build:
context: ./mytestapp
dockerfile: Dockerfile
args:
REACT_APP_WEATHER_BASE_URL: ${REACT_APP_WEATHER_BASE_URL}
REACT_APP_TESTENV: ${REACT_APP_TESTENV}
REACT_APP_NEWTESTENV: ${REACT_APP_NEWTESTENV}
ports:
- "8900:80"
myconfig.env
REACT_APP_WEATHER_BASE_URL=http://localhost:8901
REACT_APP_TESTENV=ThisIsForTest
REACT_APP_NEWTESTENV='New more env samples'
Dockerfile
FROM node:22-alpine AS base
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine AS final
WORKDIR /usr/share/nginx/html
EXPOSE 80
# Define build arguments
ARG REACT_APP_WEATHER_BASE_URL
ARG REACT_APP_TESTENV
ARG REACT_APP_NEWTESTENV
# Set environment variables at build time
ENV REACT_APP_WEATHER_BASE_URL=${REACT_APP_WEATHER_BASE_URL}
ENV REACT_APP_TESTENV=${REACT_APP_TESTENV}
ENV REACT_APP_NEWTESTENV=${REACT_APP_NEWTESTENV}
COPY --from=base /app/build /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]
React component .jsx
import { useEffect, useState } from "react";
import axios from "axios";
export const MyBaseUrl = process.env.REACT_APP_WEATHER_BASE_URL;
export default function MyDemoPage() {
const [weatherList, setWeatherList] = useState([]);
const [error, setError] = useState("");
const [loading, setLoading] = useState(true);
useEffect(() => {
console.log("REACT_APP_WEATHER_BASE_URL: " + MyBaseUrl);
console.log('REACT_APP_TESTENV ' + process.env.REACT_APP_TESTENV)
console.log('REACT_APP_NEWTESTENV ' + process.env.REACT_APP_NEWTESTENV)
const fetchData = async () => {
const weatherforecaast = "/weatherforecast";
console.log(MyBaseUrl + "base url")
let getForecastUrl = `${MyBaseUrl}${weatherforecaast}`;
console.log(getForecastUrl);
try {
setError("");
let result = await axios.get(getForecastUrl);
console.log(JSON.stringify(result.data));
setWeatherList(result.data);
} catch (ex) {
setError(ex.message);
} finally {
setLoading(false);
}
}
fetchData();
}, []);
if (loading) return <p>Loading...</p>
if (error) return <p>{error}</p>
return (<>
<p>{JSON.stringify(weatherList)}</p>
</>);
}
I am using Win 10, Docker Desktop & Docker hub.
Command:
docker-compose up --build -d
I have followed docker-docs but no luck somewhere something I am missing. I tried setting up hard-coded value in dockerfile that is working. Also I tried settings ENV variables without using Args that is also not working.
Can someone suggest what I am missing?
FYI,