node.js - 如何在 php/apache 服务器上部署 nodejs 应用程序?

标签 node.js apache nginx lighttpd

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

最佳答案

在 NodeJS 中,您可以使用预先存在的东西,例如 express,或者基本上使用自己的网络服务器,尽管听起来令人生畏,但实际上在 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,您可以使用它们将请求转发到您的 Node 进程。 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>

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 上运行的 Node 进程。

这里的想法是,您使用网络服务器来提供静态文件(例如 css),并使用 Node 进程来提供应用程序。

关于node.js - 如何在 php/apache 服务器上部署 nodejs 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32605232/

相关文章:

c++ - Node.js 6 插件将 Buffer.from() 转换为 const UInt8*

javascript - 相当于 fopen/fprintf 的 Node.js

Apache 错误 : AH00526 Invalid Mutex directory in argument file:${APACHE_LOCK_DIR} (Apache2 Ubuntu VPS Server))

nginx - 如何让我的 Dreamweaver 站点使用我的 nginx docker 容器作为 Web 测试服务器?

ruby-on-rails - 多个 redmine 实例最佳实践

javascript - Node.js:将 base64 编码的图像响应为 JSON

javascript - Express:router.post 和 router.get 之间共享逻辑

apache - 如何使用 lua 获取 HTTP 响应体?

java - 为 Log4J2 + Apache HttpClient 启用调试日志记录

node.js - 将 Nginx 设置为 Nodejs 和 Django 的代理