Hosting multiple Node.JS applications recognizing subdomains with a proxy server - javascript

I am trying to redirect certain subdomains to a specific port on my ubuntu AWS EC2 virtual server. Already tried it with DNS and that wouldn't work so based on the following topics, Default route using node-http-proxy? and How do I use node.js http-proxy for logging HTTP traffic in a computer?, I was trying to create a Node.JS proxy server with logging. That said I mixed it a bit up together (I'm new to Node.JS, still learning) and made the following script:
var httpProxy = require('http-proxy');
var PORT = 80;
logger = function() {
return function (request, response, next) {
// This will run on each request.
console.log(JSON.stringify(request.headers, true, 2));
next();
}
}
var options = {
// this list is processed from top to bottom, so '.*' will go to
// 'http://localhost:3000' if the Host header hasn't previously matched
router : {
'dev.domain.com': 'http://localhost:8080',
'beta.domain.com': 'http://localhost:8080',
'status.domain.com': 'http://localhost:9000',
'health.domain.com': 'http://localhost:9000',
'log.domain.com': 'http://localhost:9615',
'^.*\.domain\.com': 'http://localhost:8080',
'.*': 'http://localhost:3000'
}
};
// Listen to port 80
httpProxy.createServer(logger(), options).listen(PORT);
console.log("Proxy server started, listening to port" + PORT);
Well what happens is that I keep getting the following error and can't figure out how to put this to work:
$node proxyServer.js
Proxy server started, listening to port80
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1023:19)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at ProxyServer.listen (/home/ubuntu/QuantBull-Project/node_modules/http-proxy/lib/http-proxy/index.js:130:16)
at Object.<anonymous> (/home/ubuntu/QuantBull-Project/proxyServer.js:28:43)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
In short I'm trying to receive http request on port 80 and if it came from sub1.domain.com it will be redirected to portA and if it came frome sub2.domain.com it'll be redirected to portB from the same IP adress and both ports are open to the public.
Can someone explain how to fix this and explain why it happens?

Port Access:
As mentioned by the previous answer and comments the port below 1024 can't be opened by a regular user. This can be overcome by following these instruction:
If cat /proc/sys/net/ipv4/ip_forward returns 0 uncomment net.ipv4.ip_forward at the file /etc/sysctl.conf and enable these changes: sudo sysctl -p /etc/sysctl.conf, if it returns 1, skip this step;
Set up forwarding from port 80 to one desired above 1024 (i.e. port 8080): sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080;
Open up the Linux firewall to allow connections on port 80: sudo iptables -A INPUT -p tcp -m tcp --sport 80 -j ACCEPT and sudo iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
Note: To make these changes stick even when restarting the server you may check the this out.
http-proxy's routefeature is removed:
After taking care of the port access the proxy server continued without working, so after opening an issue it seemed that the routing feature was removed because, according to Nodejitsu Inc.:
The feature was removed due to simplicity. It belongs in a separate module and not in http-proxy itself as http-proxy is just responsible for the proxying bit.
So they recommended to use http-master.
Using http-master:
As described in http-master's README section, node.js is required and we need to run npm install -g http-master (may be needed to run as root depending on your setup). Then we create the config file, i.e. http-master.conf, were we add our routing details and for this specific question, the config file is as followed:
{
# To detect changes made to the config file:
watchConfig: true,
# Enable logging to stdout:
logging: true,
# Here is where the magic happens, definition of our proxies:
ports: {
# because we defined that Port 80 would be redirected to port 8080 before,
# we listen here to that port, could be added more, i.e. for the case of a
# secure connections trough port 443:
8080 : {
proxy: {
# Proxy all traffic for monitor subdomains to port 9000
'status.domain.com' : 9000,
'health.domain.com' : 9000,
# Proxy all traffic for logger subdomains to port 9615
'log.domain.com' : 9615,
# Proxy all traffic from remaining subdomains to port 8000
'*.domain.com' : 8000
},
redirect: {
# redirect .net and .org requests to .com
'domain.net': 'http://domain.com/[path]',
'domain.org': 'http://domain.com/[path]'
}
}
}
}
And we are almost done, now we just run it with: http-master --config http-master.conf and our subdomain routing should be working just fine.
Note: If you want to run the proxy server on the background I recommend using a tool like forever or pm2, and in the case of using pm2 I recommend reading this issue.

If you are running your proxy as a regular user (not root), you can't open ports below 1024. There may be a way to do this as a normal user but usually I just run such things as root.

Related

API GET Request test using Playwright

I have been trying to verify the GET status using the following code. Unfortunately, I am getting an error "apiRequestContext.get: connect ECONNREFUSED ::1:8080". Any insight would be much appreciated.
Code:
import { expect, test } from '#playwright/test';
test('Get health status', async ({ request }) => {
const response = await request.get('http://localhost:8080/myapp/actuator/health')
expect(response.status()).toBe(200)
})
Error:
apiRequestContext.get: connect ECONNREFUSED ::1:8080
Since NodeJS 17, node will prefer IPv6 over IPv4.
Verification
It might be that the service only listens on IPv4, but the client uses IPv6. Check for the words IPv4 or IPv6 in:
netstat -tulpen (on linux) or
sudo lsof -iTCP -sTCP:LISTEN -n -P 8080 | grep -i --color 8080 (on macOS).
Solutions
There are two options:
Enable IPv6 binding for the service. This depends on your service framework - search how to enable ipv6 for service XYZ in Google.
Configure NodeJS to prefer IPv4 over IPV6. Add to playwright.config.js:
import dns from "dns";
dns.setDefaultResultOrder("ipv4first");
If the service can handle, force the use of IPv4: connect to http://127.0.0.1:8080 instead of http://localhost:8080
Disable the IPv6 address for localhost for the whole machine.
Edit the hosts file (sudo vi /etc/hosts) and remove ::1 localhost.
Resources
See https://blog.apify.com/ipv4-mapped-ipv6-in-nodejs/
https://nodejs.org/api/dns.html#dnssetdefaultresultorderorder

Apache reverse proxy to Node - Connection refused: AH00957

I am trying to get a brand new cloud based server working with a default version of 20.04 server ubuntu working with apache and node. The node server appears to be running without issues reporting 4006 port is open. However I believe my apache config is not. The request will hang for a very very long time. No errors are displayed in the node terminal. So the fault must lie in my apache config seeing as we are getting the below apache errors and no JS errors.
Request error after some time
502 proxy error
Apache Error Log
[Sun Oct 17 20:58:56.608793 2021] [proxy:error] [pid 1596878] (111)Connection refused: AH00957: HTTP: attempt to connect to [::1]:4006 (localhost) failed
[Sun Oct 17 20:58:56.608909 2021] [proxy_http:error] [pid 1596878] [client 207.46.13.93:27392] AH01114: HTTP: failed to make connection to backend: localhost
vhost
<VirtualHost IP_ADDRESS:80>
ServerName api.aDomain.com
Redirect permanent / https://api.aDomain.com/
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost IP_ADDRESS:443>
ServerName api.aDomain.com
ProxyRequests on
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
ProxyPass / http://localhost:4006/
ProxyPassReverse / http://localhost:4006/
#certificates SSL
SSLEngine on
SSLCACertificateFile /etc/ssl/api.aDomain.com/apimini.ca
SSLCertificateFile /etc/ssl/api.aDomain.com/apimini.crt
SSLCertificateKeyFile /etc/ssl/api.aDomain.com/apimini.key
ErrorLog ${APACHE_LOG_DIR}/error_api.aDomain.com.log
CustomLog ${APACHE_LOG_DIR}/access_api.aDomain.com.log combined
</VirtualHost>
</IfModule>
terminal output
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `babel-node -r dotenv/config --inspect=9229 index.js`
Debugger listening on ws://127.0.0.1:9229/c1fcf271-aea8-47ff-910e-fe5a91fce6d2
For help, see: https://nodejs.org/en/docs/inspector
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
🚀 Server ready at http://localhost:4006
Node server
import cors from 'cors'
import scrape from './src/api/routes/scrape'
const express = require('express')
const { ApolloServer, gql } = require('apollo-server-express')
const { postgraphile } = require('postgraphile')
const ConnectionFilterPlugin = require('postgraphile-plugin-connection-filter')
const dbHost = process.env.DB_HOST
const dbPort = process.env.DB_PORT
const dbName = process.env.DB_NAME
const dbUser = process.env.DB_USER
const dbPwd = process.env.DB_PWD
const dbUrl = dbPwd
? `postgres://${dbUser}:${dbPwd}#${dbHost}:${dbPort}/${dbName}`
: `postgres://${dbHost}:${dbPort}/${dbName}`
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
}
async function main() {
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
}
const server = new ApolloServer({ typeDefs, resolvers })
const app = express()
app.use(cors(corsOptions))
app.use(
postgraphile(process.env.DATABASE_URL || dbUrl, 'public', {
appendPlugins: [ConnectionFilterPlugin],
watchPg: true,
graphiql: true,
enhanceGraphiql: true,
})
)
server.applyMiddleware({ app })
//Scraping Tools
scrape(app)
const port = 4006
await app.listen({ port })
console.log(`🚀 Server ready at http://localhost:${port}`)
}
main().catch(e => {
console.error(e)
process.exit(1)
})
Apache Mods Enabled
/etc/apache2/mods-enabled/proxy.conf
/etc/apache2/mods-enabled/proxy.load
/etc/apache2/mods-enabled/proxy_http.load
Updated Error Logs
[Thu Oct 21 10:59:22.560608 2021] [proxy_http:error] [pid 10273] (70007)The timeout specified has expired: [client 93.115.195.232:8963] AH01102: error reading status line from remote server 127.0.0.1:4006, referer: https://miniatureawards.com/
[Thu Oct 21 10:59:22.560691 2021] [proxy:error] [pid 10273] [client 93.115.195.232:8963] AH00898: Error reading from remote server returned by /graphql, referer: https://miniatureawards.com/
In major situations this is caused by selinux (when you have RHEL or CentOS):
# setsebool -P httpd_can_network_connect 1
link: https://unix.stackexchange.com/questions/8854/how-do-i-configure-selinux-to-allow-outbound-connections-from-a-cgi-script
Also check:
connectivity between the machines
back-end port is open
Use static IP-address (IPv4) or use host-name that are in you /etc/hosts file
I cannot exactly predict what exactly happen it could be NodeJS app crushed and no longer running or there are misconfiguration Apache files. But I strongly believe this scenario will be solved from doing things back from the top.
This step would go through updating unbuntu packages, installing needed application, configuring Apache files and setting up reverse proxy with NodeJS and Apache.
Just don't touch your NodeJS files and other code related application and they will be safe. You may also backup just to make sure. Other running application on that ubuntu server example database application like MySQL as will be just fine and still be running.
1. First we need to update ubuntu packages and install Apache, and NodeJS
$ sudo apt update
$ sudo apt install apache2 npm
2. Run this command to enable us to use Apache as a reverse proxy server
sudo a2enmod proxy proxy_http rewrite headers expires
3. Create an Apache virtual host file.
This command would will let you use ubuntu terminal as your text editor follow the guide and prompt from the terminal to write.
NOTE:
Change the "yourSite.com" with the domain of your site. It isn't really important should be the name of the file. But I think its better to name it after your site domain so you can recognize it.
$ sudo nano /etc/apache2/sites-available/yourSite.com.conf
4. Use the nano editor is to write your Apache config file for your site.
Notice: This part is critical so please pay attention
Change your ServerName and ServerAlias with your site domain name.
The ProxyPass and the ProxyPassReverse this has two parameters.
The first one is a back-slash "/" This an absolute path where your NodeJS should be located and since its single back-slash that means its your home directory.
The second one is the url "http://127.0.0.1:3000/" of your NodeJS application. Pay attentions to its PORT "3000" you may need to replaced it with the PORT you use in your NodeJS app.
<VirtualHost *:80>
ServerName example.com // replace this with site domain name without www at the beginning
ServerAlias www.example.com // replace this with site domain name beginning with www. + yourdomainname + .com
ProxyRequests Off
ProxyPreserveHost On
ProxyVia Full
<Proxy *>
Require all granted
</Proxy>
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:30000/
</VirtualHost>
5. disable the default Apache site and enable the new one.
$ sudo a2dissite 000-default
$ sudo a2ensite example.com.conf
6. Restart your Apache Server to apply the changes
sudo systemctl restart apache2
We could be ready at this point as we done setting up Apache as a reverse proxy, But we also need to install the npm package of your project and then run your NodeJS application.
7. The rest of the step is all related to NodeJS deployment. You may be already know this steps.
// install npm packages
npm install
// for a better experience using NodeJS in production install pm2 globally
npm install -g pm2
// Then run your NodeJS application using pm2 command
pm2 start // you should be at root of your NodeJS project folder when running this command
// run this another pm2 command to make sure your NodeJS app will re-run when it encounter downtime.
$ pm2 save
$ pm2 startup
Your Apache and NodeJS server is up and running now
Try to access your site by typing entering your site domain name in the browsers address bar
e.g http://yourSite.com
If you use a docker for your node server, then it might be set up incorrectly
I'm not an expert on this topic, but I have a similar setup; I use socket.io to serve WebSockets...
From your posts it seems you don't need to proxy WebSockets as well, the one shown in your logs seems to be only for debugging purposes (please correct me if I'm wrong).
Following the core of my Apache configuration:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://127.0.0.1:4006/$1 [P,L]
<Location />
ProxyPass http://127.0.0.1:4006/ retry=2
ProxyPassReverse http://127.0.0.1:4006/
</Location>
Another couple of suggestions.
Warning
Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large.
Source: https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#proxyrequests
I don't know which is the IPV6 setup on your host, you could try to use 127.0.0.1 rather than localhost in you Apache configuration to try forcing Apache to use IPV4.

live-server Error: listen EACCES 0.0.0.0:8080. even changing the ports not working? [duplicate]

I'm testing out an app (hopefully to run on heroku, but am having issues locally as well). It's giving me an EACCES error when it runs http.Server.listen() - but it only occurs on some ports.
So, locally I'm running:
joe#joebuntu:~$ node
> var h = require('http').createServer();
> h.listen(900);
Error: EACCES, Permission denied
at Server._doListen (net.js:1062:5)
at net.js:1033:14
at Object.lookup (dns.js:132:45)
at Server.listen (net.js:1027:20)
at [object Context]:1:3
at Interface.<anonymous> (repl.js:150:22)
at Interface.emit (events.js:42:17)
at Interface._onLine (readline.js:132:10)
at Interface._line (readline.js:387:8)
at Interface._ttyWrite (readline.js:564:14)
I don't have anything running on port 900 (or any of the other 20 ports I've tried), so this should work. The weird part is that it does work on some ports. For instance, port 3000 works perfectly.
What would cause this?
Update 1:
I figured out that on my local computer, the EACCES error is coming because I have to run node as root in order to bind to those certain ports. I don't know why this happens, but using sudo fixes it. However, this doesn't explain how I would fix it on Heroku. There is no way to run as root on Heroku, so how can I listen on port 80?
Running on your workstation
As a general rule, processes running without root privileges cannot bind to ports below 1024.
So try a higher port, or run with elevated privileges via sudo. You can downgrade privileges after you have bound to the low port using process.setgid and process.setuid.
Running on heroku
When running your apps on heroku you have to use the port as specified in the PORT environment variable.
See http://devcenter.heroku.com/articles/node-js
const server = require('http').createServer();
const port = process.env.PORT || 3000;
server.listen(port, () => console.log(`Listening on ${port}`));
#Windows
Another one reason - maybe your port has been excluded by some reasons.
So, try open CMD (command line) under admin rights and run :
net stop winnat
net start winnat
In my case it was enough.
Solution found here : https://medium.com/#Bartleby/ports-are-not-available-listen-tcp-0-0-0-0-3000-165892441b9d
Non-privileged user (not root) can't open a listening socket on ports below 1024.
Check this reference link:
Give Safe User Permission To Use Port 80
Remember, we do NOT want to run your applications as the root user,
but there is a hitch: your safe user does not have permission to use
the default HTTP port (80). You goal is to be able to publish a
website that visitors can use by navigating to an easy to use URL like
http://ip:port/
Unfortunately, unless you sign on as root, you’ll normally have to use
a URL like http://ip:port - where port number > 1024.
A lot of people get stuck here, but the solution is easy. There a few
options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``
Now, when you tell a Node application that you want it to run on port
80, it will not complain.
On Windows System, restarting the service "Host Network Service", resolved the issue.
If you are using Windows. You should try restarting Windows NAT Driver service.
Open Command Prompt as Administrator and run
net stop winnat
then
net start winnat
That's it.
It's happening because I installed Nord VPN and it was auto staring with windows.
Another approach is to make port redirection:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 900 -j REDIRECT --to-port 3000
And run your server on >1024 port:
require('http').createServer().listen(3000);
ps the same could be done for https(443) port by the way.
Spoiler alert: This answer may seems little funny.
I have spent more than 10 minutes to find out the root cause for this error in my system. I used this : PORT=2000; in my .env file.
Hope you already find it out. I had used a semicolon after declaring PORT number :'( I removed the extra sign and it started working.
I know this may not be answer for this question but hope it helps others who have faced same problem.
OMG!! In my case I was doing ....listen(ip, port) instead of ...listen(port, ip) and that was throwing up the error msg: Error: listen EACCES localhost
I was using port numbers >= 3000 and even tried with admin access. Nothing worked out. Then with a closer relook, I noticed the issue. Changed it to ...listen(port, ip) and everything started working fine!!
Just calling this out in case if its useful to someone else...
I had a similar problem that it was denying to run on port 8080, but also any other.
Turns out, it was because the env.local file it read contained comments after the variable names like:
PORT=8080 # The port the server runs at
And it interpreted it like that, trying to use port "8080 # The port the server runs at", which is obviously an invalid port (-1).
Removing the comments entirely solved it.
Using Windows 10 and Git Bash by the way.
I know it's not exactly the problem described here, but it might help someone out there. I landed on this question searching for the problem for my answer, so... maybe?
It means node is not able to listen on defined port. Change it to something like 1234 or 2000 or 3000 and restart your server.
restart was not enough! The only way to solve the problem is by the following:
You have to kill the service which run at that port.
at cmd, run as admin, then type :
netstat -aon | find /i "listening"
Then, you will get a list with the active service, search for the port that is running at 4200n and use the process id which is the last column to kill it by
: taskkill /F /PID 2652
I got this error on my mac because it ran the apache server by default using the same port as the one used by the node server which in my case was the port 80. All I had to do is stop it with sudo apachectl stop
Hope this helps someone.
Remember if you use sudo to bind to port 80 and are using the env variables PORT & NODE_ENV you must reexport those vars as you are now under root profile and not your user profile. So, to get this to work on my Mac i did the following:
sudo su
export NODE_ENV=production
export PORT=80
docpad run
I got this error on my mac too. I use npm run dev to run my Nodejs app in Windows and it works fine. But I got this error on my mac - error given was: Error: bind EACCES null:80.
One way to solve this is to run it with root access. You may use sudo npm run dev and will need you to put in your password.
It is generally preferable to serve your application on a non privileged port, such as 3000, which will work without root permissions.
reference: Node.js EACCES error when listening on http 80 port (permission denied)
this happens if the port you are trying to locally host on is portfowarded
Try authbind:
http://manpages.ubuntu.com/manpages/hardy/man1/authbind.1.html
After installing, you can add a file with the name of the port number you want to use in the following folder: /etc/authbind/byport/
Give it 500 permissions using chmod and change the ownership to the user you want to run the program under.
After that, do "authbind node ..." as that user in your project.
My error is resolved using (On Windows)
app.set('PORT', 4000 || process.env.PORT);
app.listen(app.get('PORT'), <IP4 address> , () => {
console.log("Server is running at " + app.get('PORT'));
});
Allow the NodeJS app to access the network in Windows Firewall.
My error got resolved just by changing port number in server.js
Specially in this line
const port = process.env.PORT || 8085;
I changed my port number to 8085 from 8080.
Hope it helps.
For me this issue affected all hosts and all ports on Windows in PowerShell.
Disabling Network Interfaces fixed the issue.
I had WiFi and an Ethernet connection and disabling the Ethernet Interface fixed this issue.
Open "Network Connections" to view your interfaces. Right-click and select "Disable".
This means the port is used somewhere else. so, you need to try another one or stop using the old port.
I tried every answer given above, but nothing works out, then I figured out that I forget to add const before declaring the variable in the .env file.
Before:
PORT = 5000;
HOST = "127.0.0.1";
After:
const PORT = 5000;
const HOST = "127.0.0.1";
So the possible reason for this would be related to typo in environment variables names or else not installed dotenv package .
So if there is any other error apart from typo and dotenv npm package ,then you must try these solutions which are given below:
First solution
for Windows only
Open cmd as run as administrator and then write two commands
net stop winnat
net start winnat
hope this may solve the problem ...
Second solution
for windows only
make sure to see that in your environment variable that there is no semicolon(;) at the end of the variable and there is no colon (:) after the variable name.
for example I was working on my project in which my env variables were not working so the structure for my .env file was like PORT:5000; CONNECTION_URL:MongoDbString.<password>/<dbname>; so it was giving me this error
Error: listen EACCES: permission denied 5000;
at Server.setupListenHandle [as _listen2] (node:net:1313:21)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1476:5)
at Function.listen (E:\MERN REACT\mern_memories\server\node_modules\express\lib\application.js:618:24)
at file:///E:/MERN%20REACT/mern_memories/server/index.js:29:9
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '5000;',
port: -1
}
[nodemon] app crashed - waiting for file changes before starting...
So i did some changes in my env file this time i removed the colon(:) and replaced it with equal(=) and removed semi colon at the end so my .env file was looking like this
PORT = 5000
CONNECTION_URL = MongoDbString.<password>/<dbname>
After changing these thing my server was running on the port 5000 without any warning and issues
Hope this may works...
#code #developers #mernstack #nodejs #react #windows #hostservicenetwork #http #permission-denied #EACCES:-4092
After trying many different ways, re-installing IIS on my windows solved the problem.
The same issue happened to me.
You need to check out your server.js file where you are setting your listening port. Change port number wisely in all places, and it will solve your issue hopefully.
For me, it was just an error in the .env file. I deleted the comma at the end of each line and it was solved.
Before:
HOST=127.0.0.1,
After:
HOST=127.0.0.1
Error: listen EACCES: permission denied 3000;
i add "PORT = 3000;" while "PORT = 3000" .
just semicolon";" give error
remove semicolon and project run successfully
I had a similar problem that it was denying to run on port 5000,
Turns out, it was because the env.local file contained comma(';') after variable names like:
PORT= 5000;
And it interpreted it like that, trying to use port "5000;", which is obviously an invalid port (-1). Removing the ';' entirely solved it.
I know it's not exactly the problem described here, but it might help someone out there. I landed on this question searching for the problem for my answer, so... maybe?
This worked perfectly fine for me, set your port at the bottom of the page with this code instead
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function() {
console.log('app started successfully')
});
Some times it is because of bad configuration the dot.env like: require("dotenv").config without () in your app middle ware or may be you write your port number with wrong syntax like instead of = you write : or add some other symbols in port number.

Node.js https server: Can't listen to port 443 - Why?

I'm creating a an HTTPS server for the first time in Node, and the code (see below) works for a random port like 6643 but on port 443, it won't work. I get this error:
[Debug][Server]: Initialized...
[Debug][Control Center]: Application initialized...
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1023:19)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Object.module.exports.router (/home/ec2-user/Officeball/Versions/officeball_v0.0.5/server/custom_modules/server.js:52:5)
at Object.<anonymous> (/home/ec2-user/Officeball/Versions/officeball_v0.0.5/server/control_center.js:15:59)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
This is on an Amazon Linux EC2 server. It's my understanding that once I set my domain's DNS A Name Record to the server's IP, when a user searches https://mydomain.com, the browser will look up my server's IP at port 443, which is supposedly the standard port for HTTPS traffic.
So my understanding is that I need to serve https content via port 443.
What am I doing wrong?
Here's my server code:
control_center.js (init)
/* Control Center */
//DEFINE GLOBALS
preloaded = {};
//GET DIRECT WORKING PATH
var dirPath = process.cwd();
//REQUIRE CUSTOM MODULES
var debug = new (require(dirPath +
"/custom_modules/debug"))("Control Center");
var socket = require(dirPath +
"/custom_modules/socket")(4546);
// ! this is the relevant line
var server = require(dirPath + "/custom_modules/server").router(443);
//APP INITIALIZE
debug.log("Application initialized...");
server.js
/* Server */
//REQUIRE NPM MODULES
var fs = require('fs'),
https = require('https'),
url = require('url'),
path = require('path');
//GET DIRECT WORKING PATH
var dirPath = process.cwd();
//REQUIRE CUSTOM MODULES
//Snip!
var debug = new (require(dirPath +
"/custom_modules/debug"))("Server");
//Preload requests
var preload = require(dirPath +
'/custom_modules/preload').init();
//INIT MODULE
debug.log("Initialized...");
//DEFINE MODULE VARIABLES
var options = {
key: fs.readFileSync('SSL/evisiion_private_key.pem'),
cert: fs.readFileSync('SSL/evisiion_ssl_cert.pem')
};
//LISTEN FOR PATH REQUESTS
//route requests to server
module.exports.router = function(port) {
https.createServer(options, function(req, res) {
//Snip!
}).listen(port);
};
On Linux (and, I believe, most other Unix-like operating systems), a service has to run as root to be able to bind to a port numbered less than 1024.
I've just verified it on a Node app I had lying around, and I saw exactly the same error, line for line identical barring the file paths, when I changed the port from 5000 to 443.
In development, most people will run the dev server on a higher-numbered port such as 8080. In production, you might well want to use a proper web server such as Nginx to serve static content and reverse proxy everything else to your Node app, which makes it less of an issue since Nginx can be quite happily run as root.
EDIT: As your use case requires serving some static content, then you may want to use a web server such as Nginx or Apache to handle the static files, and reverse proxy to another port for your dynamic content. Reverse proxying is quite straightforward with Nginx - here's a sample config file:
server {
listen 443;
server_name example.com;
client_max_body_size 50M;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location /static {
root /var/www/mysite;
}
location / {
proxy_pass http://127.0.0.1:8000;
}
}
This assumes your web app is to be accessible on port 443, and is running on port 8000. If the location matches the /static folder, it is served from /var/www/mysite/static. Otherwise, Nginx hands it off to the running application at port 8000, which might be a Node.js app, or a Python one, or whatever.
This also quite neatly solves your issue since the application will be accessible on port 443, without having to actually bind to that port.
It should be said that as a general rule of thumb running a service like this as root isn't a good idea. You'd be giving root access to an application which might potentially have vulnerabilities, and to any NPM modules you've pulled in. Putting it behind, for example, Nginx will mean you don't need to run it as root, and Nginx is solid and well-tested, as well as having solid performance and caching capability. In addition, Nginx will usually be faster at serving static content in particular.

Node.js EACCES error when listening on http 80 port (permission denied) [duplicate]

This question already has answers here:
Best practices when running Node.js with port 80 (Ubuntu / Linode) [closed]
(4 answers)
Closed 8 years ago.
Node.js throws following error while running on http port 80 (default port):-
Error: EACCES, Permission denied
at Server._doListen (net.js:1062:5)
at net.js:1033:14
at Object.lookup (dns.js:132:45)
at Server.listen (net.js:1027:20)
at [object Context]:1:3
at Interface.<anonymous> (repl.js:150:22)
at Interface.emit (events.js:42:17)
at Interface._onLine (readline.js:132:10)
at Interface._line (readline.js:387:8)
at Interface._ttyWrite (readline.js:564:14)
I figured out that node needs to have root access.
Conventionally we avoid giving root access in normal situation. What's the best practices for using it on port 80 (or port<1024).
This link has the same question but it has only one answer i.e. PREROUTING. While my solution provides other ways as well.
I am writing this to have all answers at one location, as I have to go thorough other resources than PREROUTING. Why not all answers at one location for sharing the knowledge
FYI: You cannot run socket on ports < 1024 with normal user permission. You need to have root access for it.
There are total 3 ways to solve the error:-
1. Give root access and run it (which is usual one)
2. Redirect to other port
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000
Then launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.
You should also edit your /etc/rc.local file and add that line minus the sudo. That will add the redirect when the machine boots up. You don't need sudo in /etc/rc.local because the commands there are run as root when the system boots.
Reference Link
3. Give Normal user capability of using sockets as root
Objective:- We are not providing full root access and only giving socket_root permission to access it by normal user to run your server on any port.
we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://localhost.
Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://localhost:3000 - notice the port number.
A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``
Now, when you tell a Node application that you want it to run on port 80, it will not complain.
Reference Link
General Info Reference link from apache

Categories