Local npm dependency "does not a contain a package.json file" in docker build, but runs fine with npm start

All we need is an easy explanation of the problem, so here it is.

I have an npm module I’m working on locally that is a dependency in a client app.

Directory structure is basically the following:

/app
  /client
    /src
      App.js
    package.json
    Dockerfile.dev
  /shared
    /contexts
      package.json
      test.js
    /hooks

My package.json is the following:

{
  "name": "web",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "contexts": "file:../shared/contexts",
    "react": "^16.10.2",
    "react-dom": "^16.10.2",
    "react-scripts": "3.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Importing with the following into client/src/App.js:

import { testImport } from 'contexts/test';

Works as expected when I run npm start.

The issue I’m running into is with running:

docker build -t sockpuppet/testapp -f Dockerfile.dev .

It fails and I get an error:

npm ERR! Could not install from "../shared/contexts" as it does not contain a package.json file.

Here is he Dockerfile.dev

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

How should I be handling local npm dependencies?

Also, adding something like the following to COPY the /shared into the image generates a COPY failed: Forbidden path outside the build context: ../shared/contexts () error:

COPY ../shared ./

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Ok, this works. I changed my Dockerfile.dev to the following:

FROM node:alpine
WORKDIR '/app'
COPY ./shared /shared
COPY ./web /app
RUN npm install
CMD ["npm", "run", "start"]

From the base project directory (where /shared and /web reside), I run:

docker build -t sockpuppet/client -f ./web/Dockerfile.dev .

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply