Where should I add start?

Hello,
I have no experience with NodeJS and I want to create a NodeJS container. The Dockerfile is as follows:

FROM node:latest

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install
RUN npm update

COPY ./ /usr/src/app

EXPOSE 3000

CMD npm run

The package.json and index.js files are as follows:

{
  "name": "docker-nodejs",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "prettify": "prettier -l --write \"**/*.js\"",
    "test": "jest",
    "dev": "nodemon --inspect=0.0.0.0:9229 -L /usr/src/app/src/index.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "pg": "^8.11.2",
    "sqlite3": "^5.1.2",
    "uuid": "^9.0.0",
    "wait-port": "^1.0.4"
  },
  "resolutions": {
    "ansi-regex": "5.0.1"
  },
  "prettier": {
    "trailingComma": "all",
    "tabWidth": 4,
    "useTabs": false,
    "semi": true,
    "singleQuote": true
  },
  "devDependencies": {
    "jest": "^29.6.2",
    "nodemon": "^3.0.1",
    "prettier": "^2.7.1"
  }
}

And:

const http = require('http')
const server = http.createServer((req, res) => {
	res.writeHead(200, { 'content-type': 'text/html' })

	if (req.url === '/') {
		res.write('<h1>Node and Nginx on Docker is Working</h1>')
		res.end()
	} else {
		res.write('<h1>404 Nout Found</h1>')
		res.end()
	}
})

server.listen(process.env.PORT || 3000, () => console.log(`server running on ${server.address().port}`))

When I run the container, I see the following error message:

Attaching to Node
Node  | npm ERR! Missing script: "start"
Node  | npm ERR! 
Node  | npm ERR! Did you mean one of these?
Node  | npm ERR!     npm star # Mark your favorite packages
Node  | npm ERR!     npm stars # View packages marked as favorites
Node  | npm ERR! 
Node  | npm ERR! To see a list of scripts, run:
Node  | npm ERR!   npm run
Node  | 
Node  | npm ERR! A complete log of this run can be found in: /root/.npm/_logs/2024-04-02T14_08_57_119Z-debug-0.log
Node exited with code 1

What is wrong?

Thank you.

You need to add start to your scripts in the package json

1 Like

Hi,
Problem solved.
I created a www directory and moved package.json and index.js into it.
I modified the package.json file as follows:

{
  "name": "nodejs-app",
  "dependencies": {
    "express": "^4.17.0"
  },
  "scripts": {
    "start": "node index.js"
  }
}

I also modified the Dockerfile as below:

FROM node:latest

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY ./www/package.json /usr/src/app/package.json
RUN npm install
RUN npm update

COPY ./www /usr/src/app
EXPOSE 3000

The YAML file is as follows:

version: '3.9'
services:
    nodejs:
      container_name: Node
      build:
         context: .
         dockerfile: Dockerfile
      command: npm start
      volumes:
        - ./www:/usr/src/app
      expose:
        - "3000"

Finally:

Node  |
Node  | > docker-nodejs@1.0.0 start
Node  | > node index.js
Node  |
Node  | server running on 3000