简体   繁体   English

我可以用低权限运行Node.JS吗?

[英]Can I run Node.JS with low privileges?

I would like to run node with a low privileges user, is it possible? 我想用低权限用户运行节点,是否可能? I need to use the framework Express.js 我需要使用框架Express.js

Yes. 是。 There are many solutions available to do this, depending on your exact needs. 根据您的具体需求,有许多解决方案可以执行此操作。

If you want to run node on port 80, you can use nginx (doesn't work with WebSockets yet) or haproxy . 如果要在端口80上运行节点,可以使用nginx(不能与WebSockets一起使用)或haproxy But perhaps the quickest and dirtiest is to use iptables to redirect port 80 to the port of your choice: 但也许最快最肮脏的是使用iptables将端口80重定向到您选择的端口:

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8003
sudo iptables -t nat -L

When you're happy, then save the config and make sure iptables comes on at boot 如果您满意,请保存配置并确保iptables在启动时启动

sudo service iptables save
sudo chkconfig iptables on

To automatically start your nodejs service as non-root, and restart it if it fails, you can utilize upstart with a script like this: 要以非root用户身份自动启动nodejs服务,并在失败时重新启动它,可以使用如下脚本的upstart

#!upstart
description "nodeapp"
author      "you"

start on started mountall
stop on shutdown

# Automatically Respawn:
respawn
respawn limit 99 5

script
   export HOME="/home/user/"
   exec sudo -u user /usr/local/bin/node /home/user/app.js 2>&1 >> /home/user/app.log
end script

If you're on an Amazon EC2 installation, or you get an error that says sudo: sorry, you must have a tty to run sudo , then you can replace your exec command with this: 如果您使用的是Amazon EC2安装,或者出现sudo: sorry, you must have a tty to run sudo错误sudo: sorry, you must have a tty to run sudo ,然后您可以用以下命令替换您的exec命令:

#!upstart
description "nodeapp"
author      "you"

start on started mountall
stop on shutdown

# Automatically Respawn:
respawn
respawn limit 99 5

script
   export HOME="/home/user/"
   #amazon EC2 doesn’t allow sudo from script! so use su --session-command
   exec su --session-command="/usr/local/bin/node /home/user/app.js 2>&1 >> /home/user/app.log" user &
end script

And, you didn't ask this question, but to keep it running forever, check out monit! 并且,你没有问这个问题,但为了让它永远运行,请查看monit! Here is a useful guide to setting up node.js with upstart and monit . 以下是使用upstart和monit设置node.js的有用指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM