Docker run npm install error

I am trying to dockerize my small reactjs app. This is my Dockerfile FROM node WORKDIR /usr/src/app COPY package.json . COPY . . EXPOSE 8080 RUN npm install // gives the error when executing...

I am trying to dockerize my small reactjs app.

This is my Dockerfile

FROM node

WORKDIR /usr/src/app

COPY package.json .

COPY . .

EXPOSE 8080

RUN npm install // gives the error when executing this step
RUN npm install react-scripts@3.4.1 -g --silent

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

And this is my package.json

{
  "name": "cyberhr",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "3d-force-graph": "^1.60.11",
    "@tensorflow/tfjs": "^1.7.2",
    "@tensorflow/tfjs-tsne": "^0.2.0",
    "d3-dsv": "^1.2.0",
    "mdbreact": "4.25.3",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-force-graph": "^1.32.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "tsne-js": "^1.0.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom"
  },
  "devDependencies": {
    "renamer": "^1.0.0",
    "rimraf": "^2.6.2"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

But it fails at the npm install step and gives the following error

Service ‘frontend’ failed to build: The command ‘/bin/sh -c npm install’ returned a non-zero code: 244

Here is a screenshot of the error in detail

enter image description here

Can someone please help me?

So it’s pretty strange, i don’t have any error, my missing module is listed in my package.json in my container, but the module is not in my node_modules folder.

Here’s my Dockerfile :

FROM node:8-alpine
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN apk add --no-cache ffmpeg opus pixman cairo pango giflib ca-certificates 
    && apk add --no-cache --virtual .build-deps python g++ make gcc .build-deps curl git pixman-dev cairo-dev pangomm-dev libjpeg-turbo-dev giflib-dev 
    && npm install 
    && apk del .build-deps
COPY . /app
CMD ["npm", "start"]

Here’s my docker-compose.yml :

version: '3'
services:
  app:
    build: .
    volumes:
      - ./:/app
      - /app/node_modules
    restart: always
    env_file:
      - .env
    links:
      - mongo
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3

  mongo:
    image: mongo
    volumes:
      - ~/data:/data/db
    restart: always

  adminmongo:
    image: mrvautin/adminmongo
    ports:
      - 1234:1234
    environment:
      - HOST=0.0.0.0

And my dependencies package.json :

"dependencies": {
    "cleverbot-node": "^0.3.11",
    "discord.js": "github:discordjs/discord.js",
    "enmap": "^4.5.0",
    "googleapis": "^36.0.0",
    "jsonfile": "^5.0.0",
    "mongoose": "^5.3.15",
    "node-gyp": "^3.8.0",
    "node-opus": "^0.3.1",
    "nodemon": "^1.18.9",
    "request": "^2.88.0",
    "xml-js": "^1.6.8",
    "ytdl-core-discord": "^1.0.2"
  },

Just to precise the missing module is «jsonfile» but this is probably because it is the last i’ve installed.
As i’ve said when i do a docker-compose build i don’t get any error but the ‘building’ of the container is abnormally long.

I’m having a hard problem getting my Docker container up, it shows some weird error in the console:

Dockerfile:

FROM node:14

WORKDIR /usr/src/app/

COPY package.json package.json
COPY server.js server.js

RUN ping -c 4 google.com
RUN  npm config set registry https://registry.npmjs.com/
RUN echo "${http_proxy}" && echo "${HTTP_PROXY}" 

RUN npm install
# COPY . .

EXPOSE 3000

CMD ['npm', 'start']

When I run the docker build command

$ docker build -t myapp .

The error I’m getting:

Sending build context to Docker daemon  947.7kB
Step 1/7 : FROM node:14
 ---> 7bef16bb2cf1
Step 2/7 : WORKDIR /usr/src/app/
 ---> Using cache
 ---> 90402606c386
Step 3/7 : COPY package.json ./
 ---> Using cache
 ---> b839b81ee876
Step 4/7 : RUN npm install
 ---> Running in 64378581f715
npm ERR! code ECONNREFUSED
npm ERR! errno ECONNREFUSED
npm ERR! FetchError: request to https://registry.npmjs.org/@slack%2fevents-api failed, reason: connect ECONNREFUSED 104.16.18.35:443
npm ERR!     at ClientRequest.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/node-fetch-npm/src/index.js:68:14)
npm ERR!     at ClientRequest.emit (events.js:315:20)
npm ERR!     at TLSSocket.socketErrorListener (_http_client.js:469:9)
npm ERR!     at TLSSocket.emit (events.js:315:20)
npm ERR!     at emitErrorNT (internal/streams/destroy.js:106:8)
npm ERR!     at emitErrorCloseNT (internal/streams/destroy.js:74:3)
npm ERR!     at processTicksAndRejections (internal/process/task_queues.js:80:21)
npm ERR!  FetchError: request to https://registry.npmjs.org/@slack%2fevents-api failed, reason: connect ECONNREFUSED 104.16.18.35:443
npm ERR!     at ClientRequest.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/node-fetch-npm/src/index.js:68:14)
npm ERR!     at ClientRequest.emit (events.js:315:20)
npm ERR!     at TLSSocket.socketErrorListener (_http_client.js:469:9)
npm ERR!     at TLSSocket.emit (events.js:315:20)
npm ERR!     at emitErrorNT (internal/streams/destroy.js:106:8)
npm ERR!     at emitErrorCloseNT (internal/streams/destroy.js:74:3)
npm ERR!     at processTicksAndRejections (internal/process/task_queues.js:80:21) {
npm ERR!   type: 'system',
npm ERR!   errno: 'ECONNREFUSED',
npm ERR!   code: 'ECONNREFUSED'
npm ERR! }
npm ERR! 
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-03-02T08_20_08_546Z-debug.log
The command '/bin/sh -c npm install' returned a non-zero code: 1

I’m on Ubuntu 20.4 and it is just a simple node app with a server.js file. let me know if you need anything else from me to get it fixed. Thank you in advance for your help!

Answer by Ryan Porter

Having trouble with building Docker image
,
How to build, package and deploy a react-native-web app in a Docker container?
,
Error while following Docker get-started part 3

More Details Refer


Answer by Louie Faulkner

When I run docker-compose up —build to build the image and start the container I get the following errors in the console and fresh react installation is failing.,When using Alpine, it’s better to use multi-stage build to include git in the build stage but not the release stage,I’ve created a Dockerfile by extending the node image in order to use it so I can create a fresh React installation from scratch

FROM node:12.16-alpine

RUN yarn global add create-react-app

WORKDIR /app
RUN npx create-react-app .

# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH

COPY package.json /app/package.json
RUN npm install --silent
RUN npm install react-scripts -g --silent

COPY . .

CMD ["npm", "start"]

Answer by Bobby Benjamin

Docker on Windows–Mounting Host Directories,The docker run command creates and runs a new container instance from the image we just created.,Updated the docker run commands to account for changes in react-scripts v3.4.1.

$ npm install -g [email protected]

Answer by Jonas Scott

We will use npm to install Create React App command line interface (CLI) globally:,Besides providing something that works out-of-the-box, this has the added benefit of providing a consistent structure for React apps.
It also provides an out-of-the-box build script and development server.,Create React App (CRA) is a tool to create a blank React app using a single terminal command.

npm test
react-scripts test --env=jsdom

Answer by Legacy Padilla

This may help spot error messages which are somehow getting swallowed,Or on the command line, add -e ‘DEBUG=*’ to your docker command.,

Can you also add the docker command you are using to bring up the container?

– akazuko
Apr 5 ’20 at 19:00

In your Dockerfile, add

ENV DEBUG=*

Instead of running npm start, run your file directly.
e.g. in your Dockerfile,

CMD ["node", "index.js"]

If this is a problem with your docker setup, running a known good container may help you discover it.

docker run --rm -it node:alpine

Your Dockerfile could also be simplified a bit.

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

Answer by Dalton Warren

More Details Refer


Answer by Tessa Lang

To solve this, I just added RUN npm install react-scripts -g —silent before the RUN yarn run build in the Dockerfile, and everything ran perfectly then on.,Lines 1-4 are the first stage of the build. In this stage, you copy all source code to the container and execute yarn run build that creates an optimized production build.,Now that we have the app running let’s create a Dockerfile in the root folder of the project. Here are the contents of the Dockerfile:

npm install create-react-app --global

Answer by Jedidiah Kramer

Most cloud providers offer a way to deploy a static site. A built React app is just JavaScript, HTML, and CSS. They’re static files that can live on pretty much any web server. In fact, with JSX (HTML in JS) and Styled Components, you could even say it’s just JavaScript!,
Learn More About React and Docker
,? Build a Secure Blog with Gatsby, React, and Netlify

Rather than showing you how to build a React app, I’m going to cheat and use one that a colleague of mine already built. To begin, clone the repo.

git clone https://github.com/oktadeveloper/okta-react-styled-components-example.git react-docker
cd react-docker
npm install

Copy and paste the client ID into your application’s src/App.js.
The value for <yourIssuerURI> can be found in your Okta dashboard, under API > Authorization Servers. For example, mine is https://dev-133320.okta.com/oauth2/default.

function App() {
  return (
    <Router>
      <Security issuer='<yourIssuerURI>'
                clientId='<yourClientId>'
                redirectUri={window.location.origin + '/callback'}
                pkce={true}>
        <SecureRoute path='/' exact={true} component={Calendar}/>
        <Route path='/callback' component={LoginCallback}/>
      </Security>
    </Router>
  );
}

Create a Dockerfile in your root directory.

FROM node:14.1-alpine AS builder

WORKDIR /opt/web
COPY package.json package-lock.json ./
RUN npm install

ENV PATH="./node_modules/.bin:$PATH"

COPY . ./
RUN npm run build

FROM nginx:1.17-alpine
RUN apk --no-cache add curl
RUN curl -L https://github.com/a8m/envsubst/releases/download/v1.1.0/envsubst-`uname -s`-`uname -m` -o envsubst && 
    chmod +x envsubst && 
    mv envsubst /usr/local/bin
COPY ./nginx.config /etc/nginx/nginx.template
CMD ["/bin/sh", "-c", "envsubst < /etc/nginx/nginx.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"]
COPY --from=builder /opt/web/build /usr/share/nginx/html

Create an nginx.config in the same directory:

server {
    listen       ${PORT:-80};
    server_name  _;

    root /usr/share/nginx/html;
    index index.html;

    location / {
        try_files $$uri /index.html;
    }
}

Make sure your Docker daemon is running with docker ps. Then, run the following command to build your Docker image. The react-docker value can be whatever you want to name your image.

docker build -t react-docker .

When the process completes, you’ll see something along the lines of the following message:

Successfully built 3211a1255527
Successfully tagged react-docker:latest

You can now run your React app via Docker on port 3000 using the docker run command.

docker run -p 3000:80 react-docker

If you find these docker commands hard to remember, you can add a couple of scripts to your package.json file.

"docker": "docker build -t react-docker .",
"react-docker": "docker run -p 3000:80 react-docker"

Open a terminal, log in to your Heroku account, and create a new app.

heroku login
heroku create

Create a static.json file in your root directory with security headers and redirect all HTTP requests to HTTPS.

{
  "headers": {
    "/**": {
      "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://*.okta.com;",
      "Referrer-Policy": "no-referrer, strict-origin-when-cross-origin",
      "Strict-Transport-Security": "max-age=63072000; includeSubDomains",
      "X-Content-Type-Options": "nosniff",
      "X-Frame-Options": "DENY",
      "X-XSS-Protection": "1; mode=block",
      "Feature-Policy": "accelerometer 'none'; camera 'none'; microphone 'none'"
    }
  },
  "https_only": true,
  "root": "build/",
  "routes": {
    "/**": "index.html"
  }
}

Commit your changes to Git, add the Node.js + static buildpacks, and deploy your React app.

git commit -am "Configure secure headers and static buildpacks"
heroku buildpacks:set heroku/nodejs
heroku buildpacks:add https://github.com/heroku/heroku-buildpack-static.git
git push heroku master

Once the process completes, open your app in a browser using:

heroku open

You’ll be redirected to Okta and likely see the following error:

The 'redirect_uri' parameter must be an absolute URI that is whitelisted in the client app settings.

First, log in to the Container Registry.

heroku container:login

Then, create a new app.

heroku create

Add the Git URL as a new remote to your app.

git remote add docker https://git.heroku.com/<your-app-name>.git

Then, push your Docker image to Heroku’s Container Registry.

heroku container:push web --remote docker

Once the process has completed, release the image of your app:

heroku container:release web --remote docker

And, open the app in your browser:

heroku open --remote docker

To solve this, modify your nginx.config to add security headers.

server {
    listen       ${PORT:-80};
    server_name  _;

    root /usr/share/nginx/html;
    index index.html;

    location / {
        try_files $$uri /index.html;
    }

    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://*.okta.com;";
    add_header Referrer-Policy "no-referrer, strict-origin-when-cross-origin";
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    add_header X-XSS-Protection "1; mode=block";
    add_header Feature-Policy "accelerometer 'none'; camera 'none'; microphone 'none'";
}

After updating this file, run the following commands:

heroku container:push web --remote docker
heroku container:release web --remote docker

To begin, install pack. If you’re on a Mac or Linux, you can use Homebrew. If you’re on Windows, you can install its executable.

brew tap buildpack/tap
brew install pack

Then, use the following command to build a Docker image with Node.js and the static buildpack (a.k.a., the same buildpacks you used on Heroku).

pack build react-pack --builder heroku/buildpacks --buildpack 
  heroku/nodejs,https://cnb-shim.herokuapp.com/v1/heroku-community/static

Once the process completes, you should be able to run it.

docker run --rm -it --init -p 3000:3000 --env PORT=3000 okta

If you find these pack commands hard to remember, you can add them to your package.json.

"pack": "pack build react-pack --builder heroku/buildpacks --buildpack heroku/nodejs,https://cnb-shim.herokuapp.com/v1/heroku-community/static",
"react-pack": "docker run --rm -it --init -p 3000:3000 --env PORT=3000 react-pack"

Once you have an account, log in and push your image. In the example below, I’m using react-docker, but you could also use react-pack to deploy the buildpacks version.

docker login
docker image tag react-docker <your-username>/react-docker
docker push <your-username>/react-docker

This will tag it as latest by default. If you want to tag and push a particular version, you can use:

docker image tag react-docker <your-username>/react-docker:1.0
docker push <your-username>/react-docker

Then, someone else could pull and run it using:

docker run -p 3000:80 <your-username>/react-docker

To deploy an existing image to Heroku you can use docker push. You have to use the following naming convention to tag and push the image.

docker tag <image> registry.heroku.com/<app>/<process-type>
docker push registry.heroku.com/<app>/<process-type>

For example, to deploy the react-pack image, you can do:

docker tag react-pack registry.heroku.com/fierce-eyrie-08414/web
docker push registry.heroku.com/fierce-eyrie-08414/web
heroku container:release web --remote docker

Answer by Gia Jacobson

Let’s first get react up and running on our local environment using docker. Open your terminal window and let’s create a file called Dockerfile.dev with following contents:
,
Cool, we are now done here in order to check our production environment locally let’s run following command:
,
Now, that we have our local environment all set we need to get our production environement ready. Let’s now create following two files:

I assume that you already have docker installed on your local machine. Moving on let’s now install react-create-app cli tool. Open your terminal window and type following commands:

# install create-react-app
npm install -g create-react-app

# let's create a sampler react app
create-react-app reactjs-example

# let's head into our project dir
cd reactjs-example

Let’s first get react up and running on our local environment using docker. Open your terminal window and let’s create a file called Dockerfile.dev with following contents:

# get the base node image
FROM node:alpine as builder

# set the working dir for container
WORKDIR /frontend

# copy the json file first
COPY ./package.json /frontend

# install npm dependencies
RUN npm install

# copy other project files
COPY . .

# build the folder
CMD [ "npm", "run", "start" ]

Now, we have a dockerfile with all instructions that we need in order to create our docker image. Let’s now define and create our container using docker-compose-local.yml file. Open your terminal window and create docker-compose-local.yml file with following contents:

version: '3'
services: 
    frontend:
        build: 
            context: .
            dockerfile: Dockerfile.dev
        command: npm run start
        container_name: frontend
        ports:
            - "3000:3000"        
        volumes: 
            - ./:/frontend
            - /frontend/node_modules

Alright, our docker compose file defines how our container will look like and port we expose to our host machine. Let’s now create a container using this defination. Open your terminal window and run following command to create our dev env:

# create and run our container
docker-compose -f docker-compose-local.yml up -d

Open Dockerfile and add following contents:

# get the base node image
FROM node:alpine as builder

# set the working dir for container
WORKDIR /frontend

# copy the json file first
COPY ./package.json /frontend

# install npm dependencies
RUN npm install

# copy other project files
COPY . .

# build the folder
RUN npm run build

# Handle Nginx
FROM nginx
COPY --from=builder /frontend/build /usr/share/nginx/html
COPY ./docker/nginx/default.conf /etc/nginx/conf.d/default.conf

Let’s now create a new nginx config file in docker/nginx/default.conf with following contents:

server {
  listen 80;
  server_name _;

  index index.html;
  root /usr/share/nginx/html;
  
  error_log /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;
  
  location / {
    try_files $uri /index.html =404;
  }
}

Alright, we defined out nginx production config file finally we need to create docker-compose.yml  file with following contents:

version: '3'
services:          
    frontend:
        build: .     
        container_name: frontend
        ports:
            - "80:80"
        volumes: 
            - ./:/frontend
            - /frontend/node_modules

Cool, we are now done here in order to check our production environment locally let’s run following command:

# create and run a container
docker-compose up -d

Answer by Beckett Bauer

You can read more about Docker container and image concepts in the
Docker
section of the Installing Jenkins page.,Docker — Read more about installing Docker in the
Installing Docker section of
the Installing Jenkins page.
Note: If you use Linux, this tutorial assumes that you are not running
Docker commands as the root user, but instead with a single user account that
also has access to the other tools used throughout this tutorial.,
Docker — Read more about installing Docker in the
Installing Docker section of
the Installing Jenkins page.
Note: If you use Linux, this tutorial assumes that you are not running
Docker commands as the root user, but instead with a single user account that
also has access to the other tools used throughout this tutorial.

docker network create jenkins

Answer by Lillian Khan

After copying the custom Nginx configuration file we need to build and run the docker image again.,Run the docker-compose up command to start the container. The React development server will be running inside the container and will be watching the src folder.,The application should be running fine on http://localhost:3000. Now let’s verify if the client-side routing is working fine or not. For that, we need to install the react-router-dom to the application.

Let’s start by creating a React application. You can use your existing React project. For this blog post, I am creating a new React application with create-react-app.

$ npx create-react-app react-docker

Here I created a new React app named react-docker. Let’s verify the app by running the npm start command inside the project directory.

$ npm start

Dockerfile

FROM node:14-alpine

WORKDIR /app

COPY package.json ./

COPY yarn.lock ./

RUN yarn install --frozen-lockfile

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

.dockerignore

node_modules
npm-debug.log
Dockerfile
.dockerignore

Let’s build the Docker image from the Dockerfile by running the docker build command. Here we are tagging it with the name react-docker.

$ docker build -t react-docker .

After building the docker images we can verify the image by running the docker images command. We can see an image with the name react-docker is created.

$ docker images

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
react-docker        latest              6b782301e271        2 minutes ago       438MB

We can run the Docker image with the docker run command. Here we are mapping the system port 3000 to Docker container port 3000. We can verify if the application is running or not by visiting http://localhost:3000.

$ docker run -p 3000:3000 react-docker

docker-compose.yml

version: "3"

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ./src:/app/src
    ports:
      - "3000:3000"

Run the docker-compose up command to start the container. The React development server will be running inside the container and will be watching the src folder.

$ docker-compose up

We can’t ship this docker image to the production as it is not optimized and runs a development server inside. Let’s rename the Dockerfile as Dockerfile.dev and update the docker-compose.yaml file to use the Dockerfile.dev file. We will use docker-compose and the Dockerfile.dev file only for development. We will create a new Dockerfile for the production build.

$ mv Dockerfile Dockerfile.dev

docker-compose.yml

version: "3"

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    volumes:
      - ./src:/app/src
    ports:
      - "8000:8000"

Let’s first verify the React application production config by running the yarn build command to build the app for production.

$ yarn build

We can verify the production build by running it locally. I am using serve to serve the build folder files.

$ npx serve -s build

Dockerfile

FROM node:14-alpine AS builder
WORKDIR /app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build

FROM nginx:1.19-alpine AS server
COPY --from=builder ./app/build /usr/share/nginx/html

Let’s build the image again by running the docker build command and verify if the image is built or not by running the docker images command.

$ docker build -t react-docker .
$ docker build -t react-docker .
$ docker images

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
react-docker        latest              5f885aeca09e        7 seconds ago       23.1MB

The size of the production docker image will be very less in comparison to the development one. Let’s run the docker image with the docker run command. Here we are mapping the host 3000 port with the container’s port 80

docker run -p 3000:80 react-docker

The application should be running fine on http://localhost:3000. Now let’s verify if the client-side routing is working fine or not. For that, we need to install the react-router-dom to the application.

$ yarn add react-router-dom

We also need to add a few routes and links to verify. I just copied the example from the react-router website to test.

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

export default function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Users() {
  return <h2>Users</h2>;
}

Let’s verify the local setup by running the development server and visit the web page and click on every link and refresh the pages.

$ npm start

The application should be working fine on the local development server. Now try the same thing with docker-compose. First, we need to build the image again as auto-reload works only with the src folder as we only mount that. For changes outside the src folder, we need to build the image again with the docker-compose build command.

$ docker-compose build
$ docker-compose up

Now Let’s try the same thing with the production docker build. First, we need to build the docker image and run the image again.

docker build -t react-docker .
docker run -p 3000:80 react-docker

etc/nginx.conf

server {
    listen   80;
    listen   [::]:80 default ipv6only=on;

    root /usr/share/nginx/html;
    index index.html;

    server_tokens  off;
    server_name _;

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 0;
    gzip_types text/plain application/javascript text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype;

    location / {
        try_files $uri /index.html;
    }
}

We need to copy the custom Nginx configuration file to the /etc/nginx/conf.d folder. Ngnix will auto-read all the configurations from that folder.

FROM node:14-alpine AS builder
WORKDIR /app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build

FROM nginx:1.19-alpine AS server
COPY ./etc/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder ./app/build /usr/share/nginx/html

After copying the custom Nginx configuration file we need to build and run the docker image again.

$ docker build -t react-docker .
$ docker run -p 3000:80 react-docker

Hi. I am following a docker tutorial. We are building a small project where we create a small node js app, wrap it inside a docker container, and be able to access it from a browser.

The node js app index.js:

const express = require('express');

const  app  = express();

app.get('/', (req,res) => {
    res.send("Hi there");
});

app.listen(8080, () => {
    console.log("Listening on port 8080");
});

A json script:

{
    "dependencies": {
        "express" : "*"
    },
    
    "scripts":{
        "start": "node index.js"
    }
}

Dockerfile:

#specify a base image

FROM node:alpine

#install some dependencies

COPY ./ ./
run npm install -g npm@7.10.0

#set up a default command

CMD ["npm", "start"]

The image is built and tagged.

But I am getting the following error when I run

docker run <image tag>

> start
> node index.js

node:internal/modules/cjs/loader:927
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- /index.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:924:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:996:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/index.js:1:17)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/index.js' ]
}

Did not find a proper solution. Please help.

Also, I am not able to run the npm commands on my windows command terminal. Shouldn’t I be able to that since run npm install -g npm@7.10.0 is present in the script?

I have a following Dockerfile:

FROM ubuntu:18.04

RUN mkdir app && cd app
WORKDIR app/

RUN apt-get update && apt-get install -y 
    software-properties-common 
    curl 
    sudo 
    && curl -O https://hyperledger.github.io/composer/latest/prereqs-ubuntu.sh 
    && chmod u+x prereqs-ubuntu.sh 
    && ./prereqs-ubuntu.sh 
    && npm install -g  # this line failed
    && yo 
       composer-cli@0.20 
       composer-rest-server@0.20 
       generator-hyperledger-composer@0.20 
       composer-playground@0.20

    CMD /bin/bash

The prereqs-ubuntu.sh is from https://github.com/hyperledger/composer/blob/master/packages/composer-website/jekylldocs/prereqs-ubuntu.sh.

However, it says /bin/sh: 1: npm: not found on the line npm install -g when I try to build the image. But npm is installed when running prereqs-ubuntu.sh already and can be ran successfully at the end of the file (npm --version).

Also, when I remove the npm-install part from the Dockerfile (shown below) and do docker run --name test -it myimage to see if npm is installed, but it is installed.

FROM ubuntu:18.04

RUN mkdir app && cd app
WORKDIR app/

RUN apt-get update && apt-get install -y 
    software-properties-common 
    curl 
    sudo 
    && curl -O https://hyperledger.github.io/composer/latest/prereqs-ubuntu.sh 
    && chmod u+x prereqs-ubuntu.sh 
    && ./prereqs-ubuntu.sh 

    CMD /bin/bash

asked Jul 7, 2019 at 2:17

Leon Ma's user avatar

The issue is that prereqs-ubuntu.sh uses bash to install the npm. While the RUN directive uses sh to run the commands.

Where is the npm installed

root@2cd4a6af90f4:/app# type npm
npm is /root/.nvm/versions/node/v8.16.0/bin/npm

The PATH for the RUN directive

# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

answered Jul 8, 2019 at 7:05

Yuri G.'s user avatar

1

closeup photo of yellow Labrador retriever puppy

Sometimes, we want to fix ‘Cannot find module’ error for a Node.js app running in a Docker compose environment.

In this article, we’ll look at how to fix ‘Cannot find module’ error for a Node.js app running in a Docker compose environment.

How to fix ‘Cannot find module’ error for a Node.js app running in a Docker compose environment?

To fix ‘Cannot find module’ error for a Node.js app running in a Docker compose environment, we need to install our app’s dependency in the container.

To do this, we write

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

in our Dockerfile for creating our app’s container.

We copy package.json to our container with COPY package.json /usr/src/app/.

And we install the packages with RUN npm install.

Conclusion

To fix ‘Cannot find module’ error for a Node.js app running in a Docker compose environment, we need to install our app’s dependency in the container.

Web developer specializing in React, Vue, and front end development.

View Archive

Понравилась статья? Поделить с друзьями:
  • Docker php fpm error log
  • Docker msbuild error msb1009 project file does not exist
  • Docker mosquito error address not available
  • Docker logs error level
  • Docker login error response from daemon