PHP – How to host Node.js with PHP

How to host Node.js with PHP… here is a solution to the problem.

How to host Node.js with PHP

I’ve hosted my PHP on a Linux host, now I’m using node.js for live push notifications, read integration will be done by reddis. Now my question is where to host the node.js code and how to run that code and my PHP in linux hosting?

Solution

If you have something like a VPS, then you are free to install whatever you want.

A

typical stack for running PHP with node.js is

  • Nginx, as a web server, listens on port 80
  • PHP-FPM acts as a fastcgi server that listens on port 9000
  • Run the Node application on the port you want, let’s say port 3000

In your nginx html block, you define a php and a node backend

upstream php_app {
    server 127.0.0.1:9000;
}

upstream node_app {
    server 127.0.0.1:3000;
}

In your virtual hosting, you point the PHP file to the fastcgi_pass of the PHP backend

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    try_files $uri =404;
    include /etc/nginx/fastcgi.conf;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass php_app;
}

You can forward requests on the /node subfolder to the Node backend:

location /node/ {
    proxy_pass http://node_app;
    proxy_redirect off;
}

This means that the rest of the requests (for static files) are served directly by nginx.

There are several parameters that can adjust the behavior of your application, including timeouts for PHP and Node backends, which are independent of nginx timeouts. Also, since you’re talking about push notifications, I’m guessing you’re imagining something like a websocket server (like socket.io). In this case, you also need to allow the client to request protocol switching from the Node backend

location /node/ {
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_pass http://node_app;
      proxy_redirect off;
  }

Instead of using routing to proxy to Node, I use a different subdomain, but that’s up to you.

Related Problems and Solutions