Unable to start node application inside docker - node.js

While creating my node app inside docker I am getting below error
docker container run -it --rm --volume $(pwd):/usr/src/app -p 7007:3000 sample-app-dev:latest
docker: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused "exec: \"nodemon server.js\": executable f
My Dockerfile looks like below
FROM node:12
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
ENV PATH="/usr/src/app:${PATH}"
ENTRYPOINT ["nodemon server.js"]
Package.json
{
"name": "nodedocker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
server.js
const express = require( "express" );
const app = express();
const port = 3000;
app.get( "/", ( req, res ) => {
res.send( "Hello World from express JS!!" );
} );
const hobbies = [
"Swimming", "Diving", "Jogging", "Cooking", "Singing" ] ;
app.get("/hobbies", (req, res) => {
res.send(hobbies);
});
const famous_programming = [
"python", "java", "c", "c++", "JS" ] ;
app.get("/famous_programming", (req, res) => {
message = famous_programming.includes("node")? "Yaaay, Node.js" : "Yup! Node.js is a framework from JS" ;
res.send(message);
});
app.listen( port, () => {
console.log( `Node JS started on http://localhost:${port}` )
} );
I am not sure what else I am missing here, any inputs greatly appreciated.
Thank you.

You could configure the package to run nodemon server.js on start, then specify npm start in the entrypoint:
Dockerfile:
FROM node:12
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
ENV PATH="/usr/src/app:${PATH}"
ENTRYPOINT ["npm", "start"]
package.json:
{
"name": "nodedocker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
Test:
$ docker container run -it --rm q63534772
> nodedocker#1.0.0 start /usr/src/app
> nodemon server.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Node JS started on http://localhost:3000

Related

Docker & Nodejs - ReferenceError: TextEncoder is not defined

I'm encountering the following error while trying to launch my docker container:
Error:
server_1 | /usr/src/app/node_modules/whatwg-url/lib/encoding.js:2
server_1 | const utf8Encoder = new TextEncoder();
server_1 | ^
server_1 |
server_1 | ReferenceError: TextEncoder is not defined
Dockerfile:
FROM --platform=linux/amd64 node:current-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "prod"]
docker-compose.yml:
version: '3'
services:
server:
build:
context: ./server
ports:
- "3008:3002"
environment:
API_PORT: "3002"
DB_HOST: "192.168.1.211"
DB_PORT: "27018"
DB_NAME: "tutorialitems"
restart: always
index.js file:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser({ limit: '50mb' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//DB
const db = require('./models');
const dbConfig = require('./config/db.config');
try {
db.mongoose.connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('DB Connected!');
} catch (error) {
console.log('Cannot connect to DB...', error);
process.exit();
}
//Routes
require('./routes/crud.routes')(app);
app.get('/', (req, res) => {
res.json("Server is Running")
});
app.listen(process.env.API_PORT, () => {
console.log(`Server is listening on port ${process.env.API_PORT}`)
});
What I tried (but unsuccessfully):
I updated the following file: node_modules > whatwg-url > lib > encoding.js from
Initial:
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
to Updated:
const util = require("util");
const utf8Decoder = new util.TextEncoder("utf-8", { ignoreBOM: true });
package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"prod": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.5",
"nodemon": "^2.0.15"
}
}
But when I run my docker-compose, I still have the same error.
Anyone has an idea?
Thks
Mongoose v6.1.5 is working with Node 17.3.0.
Package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"prod": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.5",
"nodemon": "^2.0.15"
}
}
After updating my package.json with the Mongoose 6.1.5 version, and my Dockerfile as following:
FROM --platform=linux/amd64 node:17.3.0
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "prod"]
I run the following docker-compose commands:
docker-compose pull
docker-compose build
docker-compose up
And now it's working. It seems that docker-compose up was still using the previously build version... thus, it was not working...
package.json:
"mongoose": "^6.2.7"
DockerFile:
FROM node:17-slim
I was getting the same error, when I set the versions as above (node:16-slim to 17-slim), my problem went away. Thanks..

Error deploying Mern Stack application on Heroku

I am trying to deploy a full-stack app on heroku, i have tried couple of things but none of them worked... when i entered "heroku logs" to follow up with the errors it should me code: 'MODULE_NOT_FOUND even though the node_module's can be found in both the Root of the project and the Frontend file as well , how do i fix this error and where does it come from ?
Here's a picture of my projects structure:
server.js:
require('dotenv').config();
const path = require('path');
const express = require("express");
const productRoutes = require("./routes/productRoutes");
const connectDB = require("./config/db");
connectDB();
const app = express();
app.use(express.json());
//--------------- deployment -------
app.use("/api/products", productRoutes);
if(process.env.NODE_ENV === "production") {
app.use(express.static(path.join('../frontend/build')));
app.get('*',(req,res) => {
res.sendFile(path.resolve(__dirname,'../frontend/build','index.html'))
})
} else {
app.get("/", (req, res) => {
res.send("Api running");
})
}
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
.env:
PORT=8080
MONGO_URI=*****
NODE_ENV=production
Package.json:
{
"name": "mern-shopping-build",
"version": "1.0.0",
"description": "Shopping list built with MERN stack",
"main": "server.js",
"engines": {
"node": "16.4.1",
"npm": "7.18.1"
},
"scripts": {
"build": "cd frontend && npm run dev",
"install-client": "cd frontend && npm install",
"heroku-postbuild": "npm run install-client && npm run build",
"start": "node server.js",
"server": "nodemon backend/server.js",
"client": "npm start && cd frontend",
"dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm start --prefix frontend\""
},
"keywords": [],
"author": "Karim ",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^5.13.2"
},
"devDependencies": {
"concurrently": "^6.2.0",
"nodemon": "^2.0.9"
}
}
ProcFile:
web node server.js
I Would appreciate any kind of feedback or help, Thank you!
A Procfile is not technically required to deploy simple apps written in most Heroku-supported languages—the platform automatically detects the language and creates a default web process type to boot the application server.
Just make sure to point your root package.json main key to backend/server.js.
Most likely it would work otherwise share your Build Logs to check it further.
{
"main": "backend/server.js"
}

Docker build command does not work for Nodejs

I am new into docker.
I am using linux to run docker. Docker successfully installed. But
When I run docker command sudo docker build . I always getting the error. How can i solve the issue?
My docker file is
FROM node:14
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "node", 'app.mjs' ]
Nodejs package.json file
{
"name": "1_getting-_started_docker",
"version": "1.0.0",
"description": "",
"main": "app.mjs",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
app.mjs
import express from 'express'
import { connectToDatabase } from './helpers.mjs';
const app = express();
app.get('/', (request, response) => {
response.send('<h1>Hi there</h1>');
});
await connectToDatabase();
// https://robinwinslow.uk/fix-docker-networking-dns
The Dockerfile looks fine, so it is very likely related to the Docker installation. You should probably try to restart the docker daemon: https://docs.docker.com/config/daemon/systemd/ and/or restarting your computer.
If that doesn't work pls show your complete logs that appear on the error message.

How to run ECMAScript (mjs files) with nodemon?

I am able to run mjs files with nodejs using --experimental-modules flag.
node --experimental-modules index.mjs
package.json:
{
"name": "mjs-tests",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.mjs"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chalk": "^2.4.2",
"uuid": "^3.3.2"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
And index.mjs
import http from 'http'
const server = http.createServer((req, res) => {
res.end('hello')
})
const PORT = 5000
server.listen(PORT, () => {
console.log(`🏃‍♀️ Server is running at http://localhost:${PORT}`)
})
But if I try to
npm run dev
or (with nodemon installed globally)
nodemon index.mjs
I get this error
[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.mjs`
internal/modules/cjs/loader.js:821
throw new ERR_REQUIRE_ESM(filename);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
So, How I can enable support for ECMAScript in nodemon? Or should I use something like esm?
Offcourse yes, All you need to modify your package.json a bit
"scripts": {
"dev": "nodemon --experimental-modules index.mjs"
},

NodeJS and Webpack on Heroku

I am simply trying to deploy a very straight forward nodejs server and webpack application to heroku but i get the following error from Heroku:
2018-03-26T12:02:19.952603+00:00 app[web.1]: webpack: Compiled successfully.
2018-03-26T11:52:19.406889+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2018-03-26T11:52:19.406889+00:00 heroku[web.1]: Stopping process with SIGKILL
2018-03-26T11:52:19.486385+00:00 heroku[web.1]: Process exited with status 137
2018-03-26T11:52:19.497230+00:00 heroku[web.1]: State changed from starting to crashed
Seems like there is something wrong with the port but i am not sure what else i could do. Here is what my node looks like:
/* jshint esversion: 6 */
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);
and my package.json:
{
"name": "xxx",
"version": "1.0.0",
"description": "xxxx",
"main": "index.html",
"scripts": {
"start": "npm run serve",
"serve": "webpack-dev-server --colors --watch --inline --progress --content-base /src --config config/webpack.dev.js",
"test:js": "eslint src/js/**",
"test:scss": "stylelint src/scss/**/*.scss",
"test": "npm run test:js && npm run test:scss",
"build": "npm run build:dev",
"build:dev": "ENV=dev webpack --config config/webpack.dev.js",
"build:prod": "npm run clean && ENV=prod webpack --config config/webpack.prod.js",
"clean": "rimraf -- dist",
"clean:all": "rimraf -- node_modules dist"
},
"license": "UNLICENSED",
"repository": {
"type": "git",
"url": "git+https://github.com/xxx/xxxx.git"
},
"keywords": [
"design",
"site",
"front-end"
],
"author": "xxxx",
"dependencies": {
...
},
"devDependencies": {
...
}
}

Resources