Running NodeJs API with Apache & PM2 on Ubuntu


Use the following steps;

1. Install Apache, Node, NPM using APT
2. Install PM2 using NPM
3. Configure apache to use proxy
  • sudo a2enmod proxy
  • sudo a2enmod proxy_http
  • sudo service apache2 reload
4. Create configuration file for site as /etc/apache2/site-available/webname.conf

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        ServerName webname.com
        <Directory "/var/www/webname">
            AllowOverride All
        </Directory>
        # ServerAdmin webmaster@localhost
        DocumentRoot /var/www/webname
        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
        ProxyRequests On
        ProxyPreserveHost On
        ProxyVia Full
        <Proxy *>
                Require all granted
        </Proxy>
        <Location /api>
                ProxyPass http://localhost:port
                ProxyPassReverse http://localhost:port
        </Location>
</VirtualHost>

5. Enable website using following commands
  • sudo a2ensite webname.conf
  • sudo service apache2 reload
6. Start NodeJs service using PM2
  • pm2 start app.js --name "service name"

Comments