I would like to thank everyone who posted answers and comments.The problem that I was facing was solved using a combination of these answers and some help from other resources.
As suggested by @DavidMaze (in the comments), I started looking into webpack config present in my code. I found out that the webpack was reading all the environment variables declared inside the container.
So I started experimenting with my Dockerfile and docker-compose.yml as I realized that REACT_APP_HOST_IP_ADDRESS was not being passed as an environment variable when the react was building the code.
The first thing I changed was the Dockerfile. I statically declared the IP inside dockerfile for testing
ENV REACT_APP_HOST_IP_ADDRESS localhost.
By doing this I was able to see the value localhost inside the env variables which were read by webpack.
Now I tried passing the ENV Variable from docker-compose to dockerfile as suggested by @Alex in his answer, but it didn’t work.
So I referred to https://github.com/docker/compose/issues/5600 and changed the docker-compose.yml and Dockerfile as follows
docker-compose.yml
version: '2'
services:
nginx:
container_name: ui
build:
context: nginx/
args:
REACT_APP_HOST_IP_ADDRESS: ${IP_ADDRESS}
ports:
- "80:80"
where IP_ADDRESS is exported as an env variable.
Dockerfile
FROM node:8 as ui-builder
WORKDIR /home/ui
COPY helloworld .
RUN npm install
ARG REACT_APP_HOST_IP_ADDRESS
ENV REACT_APP_HOST_IP_ADDRESS $REACT_APP_HOST_IP_ADDRESS
RUN npm run build
FROM nginx
COPY --from=ui-builder /home/ui/build /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]
React Component
import React, { Component } from 'react';
class HelloWorld extends Component {
render() {
console.log(process.env.REACT_APP_HOST_IP_ADDRESS);
return (
<div className="helloContainer">
<h1>Hello, world!</h1>
</div>
);
}
}
export default HelloWorld;
This configuration makes available the variables passed via ARG in docker-compose to Dockerfile during the image build process and hence the variables can be in turn declared as env variables which React can use during build process provided the webpack reads the env variables.
The webpack will be able to read the env variables using DefinePlugin
https://webpack.js.org/plugins/define-plugin/.
Make sure you prefix your variables with REACT_APP_ (as seen here), otherwise it won’t be picked up by React.