How can I run node.js Express in production mode via sudo?

I’m using the npm package express
version 2.5.2 with node version .0.6.5. I appear to be running bash version 4.1.5 on Debian 4.4.5.

I’m trying to run my server in production mode but it still runs in development mode.

I run these commands in my bash shell:

$ export NODE_ENV=production
$ echo $NODE_ENV
production
$ sudo echo $NODE_ENV
production
$ sudo node bootstrap.js

I have this code inside bootstrap.js:

var bootstrap_app = module.exports = express.createServer();
//...
console.log(bootstrap_app.settings.env);

and here’s what I see printed to standard out:

development

Is this a problem with my usage, or my system?

EDIT:Thanks to ThiefMaster for his properly identifying that this issue stems from my running node as root. ThiefMaster suggested using iptables to forward from port 80 to an unprivileged port, but my system gives me an error. Moving this discussion to superuser.com or serverfault.com (link to follow)

Problem courtesy of: Aaron

Solution

Most environment variables are unset when using sudo for security reasons. So you cannot pass that environment variable to node without modifying your sudoers file to allow that variable to passt through.

However, you shouldn’t run node as root anyway. So here’s a good workaround:

If you just need it for port 80, run node on an unprivileged port and setup an iptables forward to map port 80 to that port:

iptables -A PREROUTING -d 1.2.3.4/32 -i eth0 -p tcp -m tcp --dport 80 -j DNAT --to-destination 2.3.4.5:1234

Replace 1.2.3.4 with your public IP, 2.3.4.5 with the IP node runs on (could be the public one or 127.0.0.1) and 1234 with the port node runs on.

With a sufficiently recent kernel that has capability support you could also grant the node
executable the CAP_NET_BIND_SERVICE
privilege using the following command as root:

setcap 'cap_net_bind_service=+ep' /usr/bin/node

Note that this will allow any user on your system to open privileged ports using node!

Solution courtesy of: ThiefMaster

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » How can I run node.js Express in production mode via sudo?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录