Implement Nodejs with pm2 start in Docker - node.js

I have a nodejs app. The app runs with pm2. When I execute "pm2 start app.js". pm2 is started. But when I do curl http://localhost:3000 , it says : Failed to connect to localhost port 3000: Connection refused. But port 3000 is open. I am confused, Please help me out.
My Dockerfile
FROM keymetrics/pm2:latest-alpine
# Create app directory
RUN mkdir -p /usr/cl/app
WORKDIR /usr/cl/app
# Install app dependencies
COPY package*.json ./
COPY . .
RUN npm install
RUN npm install pm2 -g
EXPOSE 3000
CMD [ "npm", "start" ]
My Package.json
{
"name": "cs",
"version": "1.0.0",
"description": "Cs",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "pm2 start app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.6.0",
"axios": "^0.18.0",
"base64-encode-decode": "0.0.3",
"body-parser": "^1.18.3",
"cors": "^2.8.4",
"csv": "^1.2.1",
"csv2sql-lite": "0.0.6",
"dotenv": "^4.0.0",
"epipebomb": "^1.0.0",
"express": "^4.16.3",
"fast-csv": "^2.4.1",
"getmac": "^1.4.1",
"ini": "^1.3.5",
"js-md5": "^0.7.3",
"multer": "^1.3.0",
"node-cache": "^4.2.0",
"node-xlsx": "^0.12.0",
"nodemailer": "^4.6.4",
"os": "^0.1.1",
"pg": "^6.4.2",
"serve-static": "^1.13.2",
"trim": "0.0.1"
}
}
Docker image and container is created. But when I do curl http://localhost:3000
Error says "Failed to connect to localhost port 3000: Connection refused. But port 3000 is open. I am confused, Please help me out.
app.js file is
"var express = require('express');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
require('dotenv').config({path: 'inireader.env'});
var app = express();
const port = 3000;
const routepostgres = require('./routes/routepostgres');
app.use(cors());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(express.static(path.join(__dirname,'public')))
app.use('/api', routepostgres);
app.listen(port, function(req, res){
console.log('Server started at port:'+ port);
});
app.get('/', function(req, res){
res.send('Welcome # browser');
console.log('Welcome # Console');
});

Related

Node js App not working on heroku some month after testing

I have read up solution from different stack overflow but non solves the problem
This end point works fine on local host and heroku some month ago but now it works fine only on local host I get this error after I try to access the end point
server.js file
'use strict';
require("dotenv").config();
require('./MongoDB/DB')
const http = require('http');
const express = require('express');
const cors = require("cors");
const mongoSanitize = require('express-mongo-sanitize');
let cookieParser = require('cookie-parser');
const app = express();
const server = http.createServer(app)
const port=process.env.PORT||5000;
const passportContol=require("./Passport/index")
app.use(cors())
app.use(cookieParser())
app.use(express.json({ limit: "1kb" }));
app.use(express.urlencoded({ extended: true,limit: "1kb"}));
app.use(
mongoSanitize({
replaceWith: '_',
}),
);
app.use(passportContol.initialize());
app.set('trust proxy', 1);
const router1=require('./Router/Account')
const router2=require('./Router/Post')
const router3=require('./Router/Request')
app.use("/",router1);
app.use("/",router2);
app.use("/",router3);
server.listen(port ,()=>console.log(`server started.... ${port}`))
package.json
{
"name": "api-campus-bet",
"version": "1.0.0",
"description": "campus-bet api for soccer betting",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server"
},
"author": "Ogbonna Chinaza",
"license": "ISC",
"dependencies": {
"axios": "^0.26.1",
"bcrypt": "^5.0.1",
"cookie": "^0.4.2",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"csurf": "^1.11.0",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"express-mongo-sanitize": "^2.2.0",
"express-rate-limit": "^6.3.0",
"ioredis": "^5.0.3",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.2.9",
"passport": "^0.5.2",
"passport-local": "^1.0.0"
},
"engines": {
"node": "16.13.1"
}
}
Procfile
web: node server.js
WHAT I HAVE DONE
I have reinstall the nodemodule i did this including package-lock.json
I have cleared heroku cache
(git commit --allow-empty -m "Purge cache"
$ git push heroku master)
I deleted the whole project on heroku and push a new one with no error message
with some other things
please I need help what have I done wrong
This problem was caused by git it was including some files which should not be included when hosting like node module and the gitignore file. I solved the problem by using the solution in this site to remove those files.
Remove node_modules from git in vscode

Deploying to GCP App Engine with React Frontend and Node backend not able to hit api routes on deployed version by works locally

I have deployed my site to google cloud platform and the react(static) part is working fine, but anytime I go to /api/mail/send to use nodemailer I either get a 404 error saying it cant be found or with some configurations in the yaml file I just a 500 error.. below is my yaml, package.json and server.js files
App.yaml
runtime: nodejs12
env: standard
basic_scaling:
max_instances: 5
idle_timeout: 5m
handlers:
- url: /api/.*
secure: always
script: auto
- url: /
static_files: client/build/index.html
upload: client/build/index.html
secure: always
- url: /
static_dir: client/build
secure: always
Package.json
{
"name": "mern",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
"install": "cd client && npm install",
"build": "cd client && npm run build"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.8.6",
"concurrently": "^5.3.0",
"husky": "^4.2.5",
"postcss-cli": "^7.1.1",
"tailwindcss": "^1.6.2"
},
"dependencies": {
"if-env": "^1.0.4",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"classnames": "^2.2.6",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-session": "^1.17.1",
"morgan": "^1.10.0",
"nodemailer": "^6.4.11"
}
}
server.js
require('dotenv').config()
const express = require("express");
const morgan = require('morgan');
const routes = require("./routes");
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3001;
// Define middleware here
app.use(morgan('dev'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Add routes, both API and view
app.use(routes);
// Serve up static assets (usually on heroku)
app.use(express.static("client/build"));
// Start the API server
app.listen(PORT, function() {
console.log(`🌎 ==> API Server now listening on PORT ${PORT}!`);
});
Thanks

React components missing after deploying MERN app to Heroku

I deployed a MERN app to Heroku (using MongoDB Atlas for database) and the home page is not rendering the login or register forms. I checked the Heroku logs for any errors and there are no errors. Also, when I inspect the elements I see the elements are there but the React components are not rendering. Only the CSS background image is rendering. Is there something off with my heroku-postbuild script? Thanks.enter image description here
Heroku app hosted at "https://glacial-gorge-15530.herokuapp.com/login". Below are my server.js and package.json files. I also added images of development vs production screenshots of the login page.
server.js
const express = require('express');
const connectDB = require('./config/db');
const path = require('path');
const app = express();
//Connect Database
connectDB();
//Init middleware
app.use(express.json({ extended: false }));
//Define routes
app.use('/api/users', require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/recipes', require('./routes/recipes'));
//Serve static assets in production
if(process.env.NODE_ENV === 'production') {
//Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => res.sendFile(path.resolve(__dirname,'client', 'build', 'index.html')));
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
package.json
{
"name": "favorite-recipes-2",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"client": "0.0.1",
"config": "^3.3.1",
"create-react-app": "^3.4.1",
"express": "^4.17.1",
"express-validator": "^6.6.0",
"jsonwebtoken": "^8.5.1",
"materialize-css": "^1.0.0-rc.2",
"mongoose": "^5.9.20",
"react-transition-group": "^4.4.1"
},
"devDependencies": {
"concurrently": "^5.2.0",
"nodemon": "^2.0.4"
}
}
Screenshots of login page in production environment
Screenshots of login page in development environment
Your .form-container element has an opacity of 1%, which is why the elements are invisible.
.form-container {
background-color: #e7e3e3;
opacity: 1%;
}
Remove opacity: 1%.

front end not being deployed in Heroku

I'm trying to deploy my first MERN website to heroku. I have been following different tutorials but I am having trouble connecting the front end with the back end, although they connect fine in development mode.
Just to clarify: the only one that is bein deployed is the server side. I am not being able to deploy the front end.
client's package.json proxy:
"proxy": "http://localhost:5000"
Server package.json:
{
"name": "pictshare",
"version": "1.0.0",
"description": "Image Sharing Application",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server",
"build": "cd client && npm run build",
"install-client":"cd client && npm install",
"heroku-postbuild":"npm run install-client && npm run build",
"client": "npm start --prefix client",
"dev": "concurrently -n 'server,client' -c 'red, green' \"npm run server\" \"npm run client\""
},
"author": "",
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"config": "^3.3.1",
"ejs": "^3.0.2",
"express": "^4.17.1",
"express-validator": "^6.4.0",
"form-data": "^3.0.0",
"gravatar": "^1.8.0",
"gridfs-stream": "^1.1.1",
"jsonwebtoken": "^8.5.1",
"merge-images": "^1.2.0",
"method-override": "^3.0.0",
"moment": "^2.24.0",
"mongoose": "^5.9.7",
"multer": "^1.4.2",
"multer-gridfs-storage": "^4.0.2",
"node": "^13.12.0",
"nodemailer": "^6.4.6",
"path": "^0.12.7",
"react-draggable": "^4.2.0",
"request": "^2.88.2"
},
"devDependencies": {
"concurrently": "^5.1.0",
"minimist": "^1.2.5",
"nodemon": "^2.0.2"
}
}
Server.js:
const express = require('express');
const connectDB = require('./config/db');
const app = express();
const bodyParser = require('body-parser')
connectDB();
//Initialize Middleware
app.use(express.json({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', (req, res) => res.send('API Running'));
...
app.use('/api/posts', require('./routes/api/posts'));
if (process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Mongoose:
const mongoose = require('mongoose');
const config = require('config');
const db = process.env.MONGODB_URI || config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log('MongoDB Connected...');
} catch(err) {
console.error(err.message);
process.exit(1);
}
}
module.exports = connectDB;
I really appreciate any ideas or points of views!!
Thank you so much everyone!
Maybe you already did the job, let me point out a thing here in your code:
app.use(express.static('client/build'))
you maybe need to put like this :
const app = express();
const path = require('path');
app.use('/static', express.static(path.join(`${__dirname}/client/build`)));
then just send the file when the server is online:
app.get('/*', (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/`));
});
If you have .env file. Try adding this NODE_ENV = production in it.

Cordova: Cannot find modulde body-parser

I have run this command on my root console
npm install --save
At the root of my folder
This is a snippet from my ionic-gcm.js
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
var server = app.listen(3000, function(){
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
});
When I run this command, node ionic-gcm.js
I keep getting this error
Error: Cannot find module body-parser
===============================package.json======================
{
"name": "ionic-gcm",
"version": "1.0.0",
"description": "ionic-gcm: An Ionic project",
"dependencies": {
"express": "^4.13.3",
"gulp": "^3.5.6",
"gulp-concat": "^2.2.0",
"gulp-minify-css": "^0.3.0",
"gulp-rename": "^1.2.0",
"gulp-sass": "^1.3.3",
"node-gcm": "^0.11.0",
"server": "0.0.3"
},
"devDependencies": {
"bower": "^1.3.3",
"gulp-util": "^2.2.14",
"shelljs": "^0.3.0"
},
"cordovaPlugins": [
"org.apache.cordova.device",
"org.apache.cordova.console",
"com.ionic.keyboard",
"cordova-plugin-whitelist"
],
"cordovaPlatforms": [
"android"
]
}
you are missing body-parser. just type
npm install --save body-parser

Resources