If like me, you are heavily invested in an Apache web server environment and want to move into node.js, there are two several approaches:
- Apache First: Have the Apache server receive all requests, then route certain ones to the node.js server(s)
- Node First: Have a node.js server receive all requests, then route certain ones to the appropriate Apache or node.js server(s)
- nginx: This is a more modern server than Apache and can handle sockets as it is inherently a reverse proxy server by design
Here we only consider the the Apache First option: It is not a viable option to completely migrate a new hosting infrastructure.
The key idea is to set up your Apache server as a Reverse Proxy
I am mainly interested in tunneling web-sockets messages. This requires Apache 2.4+ and you must enable the module
mod_proxy_wstunnel
which in turn requires mod_proxy
.
Configure Apache
In httpd.conf
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:8080/$1 [P,L]
ProxyRequests Off
ProxyPreserveHost On
ProxyVia Full
<Proxy *>
Require all granted
</Proxy>
ProxyPass /socket.io http://localhost:8080/socket.io
ProxyPassReverse /socket.io http://localhost:8080/socket.io
Windows Batch file to launch node server
cd /www/thaidrills/public_html/apps/node/chess
node server.js
@if not %ERRORLEVEL%==0 goto hell
@if not "%1" == "" goto heaven
:heaven
@echo Heaven!
@goto end
:hell
@echo Error: %ERRORLEVEL%
@goto end
:end
@pause
PM2 to launch node server
Use PM2
to keep the socket server running in the background: PM2 will relaunch the app if it crashes or the server reboots.
It's AWESOME!!!!
Install PM2: See Ubuntu Notes: Install node.js and PM2 for instructions on installing node.js on Ubuntu.
$ npm install pm2 -g
You can start any application (Node.js, Python, Ruby, binaries in $PATH...) like that:
$ pm2 start app.js
To list all running applications:
$ pm2 list
Managing apps is straightforward:
$ pm2 stop <app_name|namespace|id|'all'|json_conf>
$ pm2 restart <app_name|namespace|id|'all'|json_conf>
$ pm2 delete <app_name|namespace|id|'all'|json_conf>
To have more details on a specific application:
$ pm2 describe <id|app_name>
To monitor logs, custom metrics, application information:
$ pm2 monit