Containerizing React Application
Create a dockerfile
I started by creating a dockerfile that will define how my react app will look like as a container.
FROM node:14.17-alpine AS client_build
WORKDIR /usr/src/app
COPY package.json .
COPY package-lock.json .
RUN npm install
COPY . .
RUN npm run build
FROM nginx AS nginx_build
COPY --from=client_build /usr/src/app/build /usr/share/nginx/html
EXPOSE 80
With this dockerfile, every time that I build the image the following will happen in the first stage:
- It will use
node:14.17-alpine
as its base image for the first stage - It will set up a work directory in
/usr/src/app
- It will copy
package.json
into the work directory - It will copy
package-lock.json
into the work directory - It will run an
npm install
- It will copy everything from current folder (local machine) to the working directory (container)
- It will run an
npm build
. This command will create a production optimized build of our react app, and store it in the/build
folder inside of the current working directory
After the above steps are completed, I should have a fresh build of my current react app in the usr/src/app/build
folder in my container. Then the second stage will do the following:
- It will use
nginx
as its base image - It will copy the contents of the
usr/src/app/build
folder, into the/usr/share/nginx/html
folder. This will allow nginx to serve our react app - It will expose port 80 of the container
When these two stages are complete, you should be able to run a docker build and then a docker run to execute your react app as a container
Demo: Adding dockerfile to docker-compose
After creating the docker image, I am now able to run my react app as a container. This means that I can use an orchestrator like docker (or even kubernetes) to orchestrate this app alongside other containers. To run this image in docker compose, you can do the following:
version: '3' services: client: container_name: portfolio_client build: context: <path-where-your-react-app-is> dockerfile: <path-where-your-docker-file-is> # Path relative to the context and not the root folder
Conclusion
Docker is a great way to build applications that can be run almost anywhere with little to no preparation. To run a docker container you only have to use the docker run
command, pass in necessary arguments if needed (e.g. env variables, port mappings, etc.), and then specify the container name docker run <args> <name>
.