Cannot open a React app in the browser after dockerising

6/25/2019

I'm trying to dockerise a react app. I'm using the following Dockerfile to achieve this.

# base image
FROM node:9.4

# set working directory
WORKDIR /usr/src/app

# install and cache app dependencies
COPY package*.json ./
ADD package.json /usr/src/app/package.json
RUN npm install

# Bundle app source
COPY . .

# Specify port
EXPOSE 8081

# start app
CMD ["npm", "start"]

Also, in my package.json the start script is defined as "scripts": { "start": "webpack-dev-server --mode development --open", .... }

I build the image as:

docker build . -t myimage

And I finally run the image, as

docker run IMAGE_ID

This command then runs the image, however when I go to localhost:8080 or localhost:8081 I dont see anything.

However, when I go into the docker container for myimage, and do curl -X GET http:localhost:8080 I'm able to access my react app.

I also deployed this on google-kubernetes and exposed a load-balancer service on this. However, the same thing happened, I cannot access the react-app on the exposed endpoint, but when I logged into the container, and made curl request, I was getting back the index.html.

So, how do I run the image of this docker image so that I could access the application through a browser.

-- Khadar111
docker
dockerfile
google-kubernetes-engine
kubernetes
reactjs

1 Answer

6/25/2019

When you use EXPOSE in Dockerfile it simply states that the service is listening on the specified port (in your case 8081), but it does not actually create any port forwarding.

To actually forward traffic from host machine to the service you must use the -p flag to specify port mapping

For example: docker run -d -p 80:8080 myimage would start a container and forward requests to localhost:80 to the containers port 8080

More about EXPOSE here https://docs.docker.com/engine/reference/builder/#expose


UPDATE

So usually when you are developing node applications locally and run webpack dev-server it will listen on 127.0.0.1 which is fine since you intend to visit the site from the same machine as it is hosted. But since in docker the container can be thought of as a separate instance that means you need to be able to access it from the "outside" world which means that it is necessary to reconfigure the dev-server to listen on 0.0.0.0 (which basically means all IP addresses assigned to the "instance")

So by updating the dev-server config to listen on 0.0.0.0 you should be able to visit your application from your host machine. Link to documentation: https://webpack.js.org/configuration/dev-server/#devserverhost

-- Kārlis Ābele
Source: StackOverflow