I am trying to deploy a NodeJS live streaming server which works on heroku built on rtmp server using node-media-server and socket.io. I am facing issue in starting the node-media-server since it needs 2 ports to run as per config format:
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000,
allow_origin: '*'
}
};
var nms = new NodeMediaServer(config)
nms.run();
I've tried deploying app on new heroku app by following official guide. Since Heroku provides only one port per dyno, it gives me these logs on my heroku app dashboard:
2020-04-07T23:08:24.289041+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media Trans Server startup failed. ffmpeg:/usr/local/bin/ffmpeg cannot be executed.
2020-04-07T23:08:24.290753+00:00 app[web.1]: (node:23) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2020-04-07T23:08:24.291397+00:00 app[web.1]: listening on port 19586
2020-04-07T23:08:24.292059+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media Rtmp Server Error: listen EADDRINUSE: address already in use :::19586
2020-04-07T23:08:24.292694+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media Http Server Error: listen EADDRINUSE: address already in use :::19586
2020-04-07T23:08:24.293383+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media WebSocket Server Error: listen EADDRINUSE: address already in use :::19586
2020-04-07T23:08:24.682440+00:00 heroku[web.1]: State changed from starting to up
2020-04-07T23:08:24.693405+00:00 app[web.1]: Connected to the database
I need to know how I can deploy my app on heroku (or any other alternative) to make it available in production mode. My server works fine on my MacBook Pro.
Here's my code:
const { NodeMediaServer } = require('node-media-server');
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const http = require('http');
const fs = require('fs');
const bodyParser = require('body-parser');
const path = require('path');
const process = require('process')
const port = process.env.PORT||5000
const port2 = process.env.PORT||8000
const port3 = process.env.PORT||8001
const server = http.createServer(app);
const io = require('socket.io').listen(server);
require('./app/controllers/socketIO')(io);
mongoose.Promise = global.Promise;
global.appRoot = path.resolve(__dirname);
mongoose.connect(
"mongodb://databasecredentials",
{ useNewUrlParser: true },
err => {
if (err) {
console.log(err);
} else {
console.log('Connected to the database');
}
}
);
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
app.set('socketio', io);
app.set('server', server);
app.use(express.static(`${__dirname}/public`));
server.listen(port, err => {
if (err) {
console.log(err);
} else {
console.log(`listening on port ${port}`);
}
});
const nodeMediaServerConfig = {
rtmp: {
port: port2,
chunk_size: 60000,
gop_cache: true,
ping: 60,
ping_timeout: 30
},
http: {
port: port3,
mediaroot: './media',
allow_origin: '*'
},
trans: {
ffmpeg: '/usr/local/bin/ffmpeg',
tasks: [
{
app: 'live',
ac: 'aac',
mp4: true,
mp4Flags: '[movflags=faststart]'
}
]
}
};
var nms = new NodeMediaServer(nodeMediaServerConfig);
nms.run();
I'm not very familiar with Heroku, but in the first line of the logs it states:
[ERROR] Node Media Trans Server startup failed. ffmpeg:/usr/local/bin/ffmpeg cannot be executed.
you need to install ffmpeg on the machine running the code. This is the first step to get your server starting (this might not fix all the problems you're having but this is the first thing you need to start with).
I'm trying to do something similar using GCP. In order to get it to run, I created a package.json file and set the start script to apt install --fix-missing --assume-yes ffmpeg && node app.js as a temporary workaround:
{
"name": "app-service-hello-world",
"description": "Simple Hello World Node.js sample for Azure App Service",
"version": "0.0.1",
"private": true,
"license": "MIT",
"author": "Microsoft",
"scripts": {
"start": "apt install --fix-missing --assume-yes ffmpeg && node app.js"
},
"dependencies": {
"node-media-server": "^2.1.9"
}
}
This might help you adding ffmpeg correctly to your Heroku environment: Install FFMPEG on Heroku
Related
I have completed a project and trying to deploy on heroku. I am using Reactjs frontend and express Nodejs with mongoose and mongodb in the Backend. It works on localhost but when I run Build it and try to deploy it on heroku it gives an application error.
Here is my backend connection code:
require('dotenv').config();
const express = require('express')
const session = require("express-session")
const bodyParser = require('body-parser')
const cors = require('cors')
const zomatoRoutes = require('./Routes/zomato')
const paymentRoutes = require('./Routes/payments')
const mongoose = require('mongoose')
const passport = require("passport")
const MongoStore = require('connect-mongo');
const uri = process.env.MONGO_URI || 'mongodb://localhost/zomato';
console.log(uri,'this is the mongo Atlas uri if connected using that !!!')
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName:'zomato1'
}
const connectDB = async () => {
await mongoose.connect(uri, options ).then(() => {
console.log('mongo connected')
}).catch( e => console.log(e))
}
connectDB().then(() => {
app.listen( process.env.PORT ||5252 , () => {
console.log("express app is up and running on port 5252");
})
})
I also have mongo session store the mongoose session when user logs in
app.use(session({
secret: "this is unambigous secret",
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24*60*60*1000 },
store : MongoStore.create({
client: mongoose.connection.getClient(),
dbName:'zomato1',
ttl: 14 * 24 * 60 * 60
})
}));
app.use(passport.initialize());
app.use(passport.session());
It gives me MongoNotConnectedError: MongoClient must be connected to perform this operation error when I try to deploy using
git push heroku master:main
full error tail :
mongodb+srv://vishal_torne_22:********#db-first-hernode.zu6btrs.mongodb.net/<DBNamecomeshere>?retryWrites=true&w=majority this is the mongo Atlas uri if connected using that !!!
2022-07-31T11:19:34.581869+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:367
2022-07-31T11:19:34.581876+00:00 app[web.1]: throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
2022-07-31T11:19:34.581877+00:00 app[web.1]: ^
2022-07-31T11:19:34.581877+00:00 app[web.1]:
2022-07-31T11:19:34.581878+00:00 app[web.1]: MongoNotConnectedError: MongoClient must be connected to perform this operation
2022-07-31T11:19:34.581878+00:00 app[web.1]: at getTopology (/app/node_modules/mongodb/lib/utils.js:367:11)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at Collection.createIndex (/app/node_modules/mongodb/lib/collection.js:258:82)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at MongoStore.setAutoRemove (/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:147:35)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at /app/node_modules/connect-mongo/build/main/lib/MongoStore.js:128:24
2022-07-31T11:19:34.581882+00:00 app[web.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-07-31T11:19:34.581882+00:00 app[web.1]:
2022-07-31T11:19:34.581882+00:00 app[web.1]: Node.js v17.9.1
2022-07-31T11:19:34.703486+00:00 heroku[web.1]: Process exited with status 1
2022-07-31T11:19:34.791551+00:00 heroku[web.1]: State changed from starting to crashed
I am using Mongoose to connect the Mongodb, It works on localhost without heroku but when I deploy it using heroku, It asks me to use MongoClient. Is it a requirement to use mongoClient on Heroku 20 stack, I also get warning to upgrade to new Heroku version, I tried to upgrade heroku using npm upgrade heroku to the specifed version it shows successful but again rolls back to heroku 20 stack.
here's what I tried but researching the previous answers :
I added on my mongodb atlas the whitelist 0.0.0.0/0 (includes you current IP address)
I tried to make the mongoose code async so that it connect firsts the database then app listens to the port.
changed the engine version so that it supports latest node and npm version on Heroku like:
{
"version": "1.0.0",
"engines": {
"node": "17.x",
"npm":"8.x"
}
}
Is it a requirement to use MongoClient on heroku 20 stack ? as the Error shows... and why it is showing error on Mongoose.connect()
Thanks in advance..!
As you say it runs fine in your local environment, the issue may be fixed by adding process.env.MONGO_URL to the config vars of your application, as the issue may originate when Heroku tries to connect to your MongoDB, but does not achieve this connection due to an invalid url that is stored in an env variable on your local device.
I am working on a project with Node.js, React.js and MongoDB.
When I send request to server, I get the following error:
Error occurred while trying to proxy request /api/auth/login from localhost:3000 to http://localhost:6000 (ECONNRESET).
I have my client running at port 3000, server at port 6000 locally. Here is the client side proxy middleware setup code:
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/api/", { target: "http://localhost:6000", "secure": "false" }));
};
I have tried using 127.0.0.1 inplace of localhost, but didn't work.
The project works fine in Windows laptop. But, it is having problem with M1 Mac.
Any guidance would be of great help to me.
I got the same error using M1.
This code started working correctly for me.
http://localhost:3000/ -> http://127.0.0.1:3000/
server.js
"use strict";
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const PORT = 9090;
const HOST = "0.0.0.0";
const app = express();
app.use(
createProxyMiddleware("/", {
target: "http://127.0.0.1:3000/",
})
);
app.listen(PORT, HOST);
packege.json
{
"name": "web",
"version": "1.0.8",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"http-proxy-middleware": "^2.0.6"
}
}
node v18.11.0
npm 8.19.2
Server at "http://127.0.0.1:3000/" - default configuration for create-react-app ("react-scripts": "^5.0.1")
I changed the version of Node.js to 14.9.0 and it worked.
These are the solutions found in the internet that didn't work for me:
Changing node.js version to other stable version 16 or 18
specifying an IPv4 address like this on server (because I can see my server was running on IPv6): server.listen(13882, "0.0.0.0", function() { });
Removing proxy entry from the Package.json file
Updating to {target: "http://localhost:6000/"} OR {target: "https://localhost:6000/"} OR {target: "http://127.0.0.1:6000"} OR
{'http://[::1]:6000'} OR {app.use(proxy("/api/", {target:"http://localhost:6000",secure: false,changeOrigin: true}));}
I have this entry in package.json file "proxy": "http://localhost:6000"
This is my setupProxy.js file
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/api/", { target: "http://localhost:6000" }));
};
My api has stopped working, previously it worked fine and as far as i am aware I have changed nothing. When i tested my endpoint i received an internal server error.
Here is a link to my hosted api https://frozen-scrubland-34339.herokuapp.com/api
I have just checked some of my other apis and none are working either, same message. it appears my code isnt the issue but postgres itself?
Any help on what to do would be appreciated
When i tried to npm run prod to re-push it to heroku i received: 'Error: The server does not support SSL connections'
Again this was never an issue previously when it worked.
I imagine i have changed something with heroku itself by accident?
app.js
const express = require("express");
const app = express();
const apiRouter = require("./routers/api-router");
const cors = require("cors");
const {
handle404s,
handlePSQLErrors,
handleCustomError,
} = require("./controllers/errorHandling");
app.use(cors());
app.use(express.json());
app.use("/api", apiRouter);
app.use("*", handle404s);
app.use(handlePSQLErrors);
app.use(handleCustomError);
module.exports = app;
connection.js
const { DB_URL } = process.env;
const ENV = process.env.NODE_ENV || "development";
const baseConfig = {
client: "pg",
migrations: {
directory: "./db/migrations",
},
seeds: {
directory: "./db/seeds",
},
};
const customConfigs = {
development: { connection: { database: "away_days" } },
test: { connection: { database: "away_days_test" } },
production: {
connection: {
connectionString: DB_URL,
ssl: {
rejectUnauthorized: false,
},
},
},
};
module.exports = { ...baseConfig, ...customConfigs[ENV] };
I am trying to implement Jaeger in the node js project. I have deployed this node js project(using docker image) and Jaegaer in k8s (kubectl create -f https://raw.githubusercontent.com/jaegertracing/jaeger-kubernetes/master/all-in-one/jaeger-all-in-one-template.yml)
Both are working individually but traces are not visible in the service
var initTracer = require('jaeger-client').initTracer;
const opentracing = require("opentracing");
const bodyParser = require('body-parser');
var config = {
'serviceName': 'user-service',
'local_agent': {
'reporting_host': 'jaeger',
'reporting_port': '6831',
},
'reporter': {
'logSpans': true
},
'sampler': {
'type': 'probabilistic',
'param': 1.0
}
};
var options = {
'tags': {
'user-service': '1.1.2'
}
};
var tracer = initTracer(config, options);
opentracing.initGlobalTracer(tracer);
console.log(tracer);
const express = require('express');
const app = express();
app.use(bodyParser.json({ type: 'application/*+json' }));
app.get('/users/:id',(req, res) => {
const span = tracer.startSpan('get user by user_id');
res.send(JSON.stringify('hello'));
span.log({'event': 'request_end'});
span.finish();
});
// Set up server
const server = app.listen(8000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Service_1 listening at http://%s:%s', host, port);
});
Have you tried looking at the logs being generated by your pods?
In my case I got the following
ERROR Failed to flush spans in reporter: error sending spans over UDP:
Error: getaddrinfo ENOTFOUND http://jaeger-agent, packet size: 984,
bytes sent: undefined
Changing it to jaeger-agent worked for me.
Also if it helps I have declared this under my jaeger image in docker-compose.yml:
+ ports: - "5775:5775/udp" - "6831:6831/udp" - "6832:6832/udp" - "5778:5778" - "16686:16686" - "14268:14268" - "9411:9411"`
I have hosted my loopback 4 application on iisnode windows web app, which is giving the port as pipe and in my loopback 4 application i am reading port as Process.env.PORT. And i am getting the error:
Cannot start the application. RangeError [ERR_SOCKET_BAD_PORT]: Port should be >= 0 and < 65536. Received \.\pipe\fde1f2c4-428f-5513-8114-c9520f1ba02d
I tried by manually giving port 80, 443 but that is not working and throwing error like
EADDRNOTAVAIL
Expected port to be a number but iisnode giving it as pipe, which loopback 4 is rejecting.
// index.js root file
const application = require('./dist');
module.exports = application;
// Run the application
const config = {
rest: {
port: (process.env.PORT|| 3000),
host: process.env.WEBSITE_HOSTNAME || "localhost",
openApiSpec: {
setServersFromRequest: true,
},
},
};
application.main(config).catch(err => {
console.error('Cannot start the application.', err);
process.exit(1);
});
// index.ts inside src
import {myApplication} from './application';
import {ApplicationConfig} from '#loopback/core';
export {myApplication};
export async function main(options: ApplicationConfig = {}) {
const app = new myApplication(options);
await app.boot();
await app.start();
const url = app.restServer.url;
console.log(`Server is running at ${url}`);
return app;
}
Please see our response in https://github.com/strongloop/loopback-next/issues/3507#issuecomment-518099844. Thanks.