DEV Community

Cover image for Dockerize a React App with node and nginx and how to push an image to Docker Hub
Luiz Calaça
Luiz Calaça

Posted on

Dockerize a React App with node and nginx and how to push an image to Docker Hub

Hi, Devs!

Let's see a React app dockerized and how to push the image the we are going to create to the Docker Hub.

React, Docker and Nginx

First if you need to search the main docker commands, look at: https://docs.docker.com/engine/reference/commandline

You need to create one specific user with the write, read and delete privileges to avoid the message The common error is the message: requested access to the resource is denied. Look at https://docs.docker.com/docker-hub/access-tokens/

After creating an access token on docker hub:

docker login -u <username>
Enter fullscreen mode Exit fullscreen mode

Creating a React App with:

npx create-react-app my-app
Enter fullscreen mode Exit fullscreen mode

We are going to use https://hub.docker.com/_/node, into the src folder we can create the Dockerfile and copy these commands.

FROM node AS prod
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
# RUN npm test - if you want to test before to build
RUN npm run build

FROM nginx:alpine AS prod
WORKDIR /usr/share/nginx/html
COPY --from=prod /app/build .
EXPOSE 80
# run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]
Enter fullscreen mode Exit fullscreen mode

Into src folder, you can create the .dockerignore and add it:

/node_modules
Enter fullscreen mode Exit fullscreen mode

Execute the Docker image build:

docker image build -t react:v1 .
Enter fullscreen mode Exit fullscreen mode

After you built an image, let’s run to verify if it is working.

docker run -dit -p 3300:80 --name react react:v1
Enter fullscreen mode Exit fullscreen mode

To get the container id:

docker container ls 
Enter fullscreen mode Exit fullscreen mode

After you got the container id you can use it and commit the container:

docker container commit <id-container> react:v1
Enter fullscreen mode Exit fullscreen mode

Let’s looking for the image that we built before and get the id:

docker images
Enter fullscreen mode Exit fullscreen mode

Looking at the output of the docker images command, we can see the repository name, tag and image id. We need to create a tag:

docker tag <image-name:tag> <your-repository>/image-name:image-name-repository

docker tag react:v1 luizcalaca/react:react
Enter fullscreen mode Exit fullscreen mode

The last is the push:

docker push <repository>/<tag>

docker push luizcalaca/react:react
Enter fullscreen mode Exit fullscreen mode

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Top comments (0)