This tutorial will show you how easy it is to create a docker image for a react application. Lets get started.
Companion Video: https://youtu.be/15HtGddstok
Pre-requisites
You need to have the following installed on your computer:
- Node.js & npm
- Docker desktop
Create a React app
Choose a suitable working folder and then execute the following command in a terminal window to create a React app named react101:
npx create-react-app react101 --use-npm
cd react101
npm start
The app will display in your default browser as shown below:
Build the React app
Stop the app by typing CTRL C. Execute the following command from a terminal window in the application's root folder to create a deployable version of the application.
npm run build
This creates the deployable artifacts in the /build folder and looks like this:
We will use the nginx web server docker base image. Create a text file named Dockerfile in your application's root folder and add to it the following:
FROM nginx:alpineWORKDIR /var/www/webCOPY build .COPY nginx.conf /etc/nginx/nginx.confEXPOSE 80
The nginx.conf configuration file is used to set the nginx document root . Add the following code to nginx.conf:
events { }http {include mime.types;server {listen 80;index index.html;location / {root /var/www/web;try_files $uri $uri/ /index.html =404;}}}
We can now build a docker image by running the following command:
docker build --tag react:1.0.0 .
You should see your docker image when you run the following docker command:
docker images
Your output will look similar to this:
react 1.0.0 8fa6896c8bb4 About a minute ago 23.1MB
Let's run the image as a container and see if we can load our react app in a browser. Run the following command to run the web app on port 8888 in a container:
docker run -d -p 8888:80 react:1.0.0
Point your browser to http://localhost:8888 and you should see your web app being served from a docker container.