我有一台专用服务器,目前在上面运行了4个PHP网站。该服务器配置有apache+nginx。每当我托管php网站时,我将文件放置在public_html文件夹中,就可以开始运行了。但是现在我想安装nodejs应用程序。我只是困惑如何处理server.js文件?以及如何让它持续运行?我应该使用pm2或forever在我的Ubuntu主机上让它永久运行吗?另外如何使用域名example.com运行网站。
在NodeJS中,您可以使用像express这样的预先存在的东西,或者基本上自己编写Web服务器,尽管听起来很令人生畏,但在NodeJS中实际上非常简单...
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(3000);
如果您希望在服务器上保持服务运行,Forever和PM2是最好的起点。Forever比PM2存在更长时间,但我认为PM2比Forever更具特色(尽管Forever使用稍微简单)。
关于apache或nginx,您可以使用它们将请求转发到您的节点进程。 http默认在80端口上运行,但是80端口已经被您的apache进程占用了。我的建议是在另一个端口(例如3000)上运行您的nodejs应用程序,并将现有的Web服务器(例如apache,ligtthpd,nginx等)用作反向代理。下面包含了一些示例设置。
Apache
<VirtualHost example.com:*>
ProxyPreserveHost On
ProxyPass /api http://localhost:3000/
ProxyPassReverse /api http://localhost:3000/
ServerName localhost
</VirtualHost>
轻量级 Web 服务器 Lighttpd
$HTTP["host"] == "example.com" {
server.document-root = "/var/www/example.com"
$HTTP["url"] =~ "(^\/api\/)" {
proxy.server = (
"" => (
(
"host" => "127.0.0.1",
"port" => "3000"
)
)
)
}
}
nginx
http {
...
server {
listen 80;
server_name example.com;
...
location /api {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
rewrite ^/api/?(.*) /$1 break;
proxy_pass http://localhost:3000;
}
...
}
}
在上面的例子中,任何对http://example.com/api的请求都将重定向到运行在端口3000上的节点进程。