我有一个专用的服务器上,我目前正在运行4个PHP网站。服务器配置为Apache+Nginx。每当我托管php网站时,我将文件放在public_html文件夹中,它就会开始运行。但现在我想安装nodejs应用程序。我只是对如何处理server.js文件感到困惑?又如何让它继续运行?我应该使用pm2还是永远保持它在我的ubuntu主机上永远运行。如何运行域名为example.com的网站
在NodeJS中,您可以使用一些预先存在的东西,比如express,或者基本上滚动您自己的webserver,这在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上运行,但apache进程已经在使用端口80。我推荐的是在另一个端口(例如3000)上运行nodejs应用程序,并使用现有的web服务器(apache、ligtthpd、nginx等)作为反向代理,我在下面提供了一个示例设置。
阿帕奇
<VirtualHost example.com:*>
ProxyPreserveHost On
ProxyPass /api http://localhost:3000/
ProxyPassReverse /api http://localhost:3000/
ServerName localhost
</VirtualHost>
灯光
$HTTP["host"] == "example.com" {
server.document-root = "/var/www/example.com"
$HTTP["url"] =~ "(^\/api\/)" {
proxy.server = (
"" => (
(
"host" => "127.0.0.1",
"port" => "3000"
)
)
)
}
}
恩吉尼克斯
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上运行的节点进程。
这里的想法是使用webserver提供静态文件(例如css),并使用节点进程提供应用程序。