Skip to content
Related Articles

Related Articles

Improve Article

How to call ‘npm start’ though docker ?

  • Difficulty Level : Easy
  • Last Updated : 04 Jul, 2021
Geek Week

The following article covers how to call npm start through docker. While doing so, we will dockerize a simple React App.

Docker is an open-source platform for running, shipping, and managing applications. It allows us to manage our infrastructure in the same way as we manage our applications. 

It runs the application in a kind of isolated environment called container. A container is lightweight and contains everything needed to run the application. Multiple containers can run on the same host, and they can also share data between them securely.

 



Creating the React Application:

  • Step 1: Create a React application using the following command.

    npx create-react-app docker-react
  • Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command.

    cd docker-react
  • Step 3: Create a file named Dockerfile in the root of your app.

Project Structure: It will look like this.

Writing the Dockerfile: Write down the following lines to your Dockerfile.

FROM node:alpine
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
CMD ["npm", "start"]

Explanation:

  • First, we load the base image node:alpine which is a lightweight Linux distribution with a node installed in it.
  • Then we copy the package.json file which contains the app’s dependencies into our working directly.
  • And then we install the dependencies and copy the project files into our working directory.
  • Finally, we run the command npm start.

Creating docker image: Run the following command from the project’s root directory. Make sure your docker daemon is running.

docker build -t <yourname/projectname> .

Steps to run the application: Run the application using following command from the root directory of your folder.

docker run -d -it -p 3000:3000 <yourname/projectname>

Here we need to map our localhost port to the one of the container which in our case is 3000.

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

My Personal Notes arrow_drop_up
Recommended Articles
Page :