如何在php/apache服务器上部署nodejs app?

Joh*_*ohn 11 apache lighttpd nginx node.js

我有一个专用服务器,我目前正在运行4个PHP网站.服务器配置了apache + nginx.每当我托管php网站时,我都会将文件放在public_html文件夹中,就这样,它就开始运行了.但现在我想安装nodejs应用程序.我只是对如何处理server.js文件感到困惑?以及如何让它继续运行?我应该使用pm2还是永远保持它在我的ubuntu主机上永远运行.另外如何使用example.com这样的域名运行网站

Kin*_*tic 14

在NodeJS中,您既可以使用像express这样的预先存在的东西,也可以基本上使用自己的网络服务器,这对于在节点中实际上是一个简单的调查来说......

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(3000);
Run Code Online (Sandbox Code Playgroud)

如果您希望在服务器上运行服务,Forever和PM2是最佳起点.永远比PM2更长,但我相信PM2比Forever功能更丰富(永远使用起来稍微简单).

关于apache或nginx,您可以使用它们将请求转发到您的节点进程.http默认运行在端口80上,hachever端口80将由您的apache进程使用.我建议在另一个端口(例如3000)上运行nodejs应用程序,并使用现有的Web服务器(apache,ligtthpd,nginx等)作为反向代理,我在下面列出了一些示例设置.

阿帕奇

<VirtualHost example.com:*>
    ProxyPreserveHost On

    ProxyPass /api http://localhost:3000/
    ProxyPassReverse /api http://localhost:3000/

    ServerName localhost
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

Lighttpd的

$HTTP["host"] == "example.com" {
    server.document-root = "/var/www/example.com"
    $HTTP["url"] =~ "(^\/api\/)" {
       proxy.server = (
            "" => (
                (
                    "host" => "127.0.0.1",
                    "port" => "3000"
                )
            )
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
        }

        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,对http://example.com/api的任何请求都将重定向到在端口3000上运行的节点进程.

这里的想法是使用webserver来提供静态文件(例如css)和用于提供应用程序的节点进程.