Node JS: Creating an Application on our CPANEL Application Manager

Creating an Application in the cPanel Application Manager

Hosting applications with cPanel is a two-step process:

  1. Install the app on the server. 
  2. Register it with the Application Manager.

We’ll look at registering an application in the next section, but first, we need to install it on the server. Users of the Git™ version control system could clone a repository with its command-line client or cPanel’s Git Version Control interface. However, to illustrate the process, we’ll create a simple single-file application.

Log in with SSH ( you need to login to our customer dashboard and open a ticket asking to open the ssh on your account ) as a cPanel user and create a new directory in their home directory. 

mkdir nodejsapp

You can call the directory anything you want. This is where your app’s code files will live. Create a file called app.js in this directory with your preferred text editor. cPanel expects the application’s entry point to be called app.js, so it’s best to stick with the standard naming convention unless you have a good reason to change it

Paste the following code and save the new file. 

const http = require('http')
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World! I am your new NodeJS app! \n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

The code sets up an HTTP server on port 3000. It responds to web requests with the message: “Hello World! I am your new NodeJS app!”  

We could go straight to the registration step, but let’s make sure the app works first. Run the following command, which executes our mini-app with EasyApache’s Node.js installation. 

/opt/cpanel/ea-nodejs10/bin/node app.js

All being well, you will see a message that says:

Server running at http://127.0.0.1:3000

Finally, open a new terminal window and log in to your server as the same cPanel user. We’ll use the curl HTTP client to send the app a request. 

curl http://127.0.0.1:3000

If it responds with “’Hello World! I am a NodeJS app on cPanel,” you can move on to the next stage: registering your Node.js app with cPanel. 

Registering Your Node.JS Application in the cPanel Application Manager

Registering tells the Passenger app manager and cPanel where to find your application and which domain you want to use. 

In cPanel, open the Application Manager, which you’ll find under Software on the main page. 

application manager on cpanel

Click the Register Application button.

In the Application Configuration table, we need to provide four pieces of information:

  • Application Name: A display name for the application. You can choose any name, but it must start with a number or letter, and it can’t contain periods.
  • Deployment Domain: The app’s domain name. The domain must already be associated with the cPanel account. 
  • Base Application URL: The app’s home page will be available at the deployment domain + the base URL. For example, if the Deployment Domain is “example.com” and you enter “nodeapp” in this field, the app will be served from “example.com/nodeapp.” The URL extension does not have to be the same as the directory that stores the app’s files. 
  • Application Path: The location of the app’s files relative to the user’s home. In our example, we created a directory in home called “nodejsapp,” so we’d enter “nodejsapp” here.

The Deployment Environment selector indicates whether the app is under development or ready for deployment in a production environment. 

Underneath the Application Configuration table is an interface for configuring environment variables. We’ll look at them in greater depth in the next section. 

For now, we’ll click the Deploy button at the bottom of the page, and cPanel will configure the app’s environment and domain. Once it’s finished, you can open your new app in a web browser at the URL you just configured: “example.com/nodeapp” in our examples. 

Unlike a real app, our one-pager has no external dependencies. If it did, cPanel Application Manager would display the Ensure Dependencies button for one-click installation. The button is only available for apps with a package.json file that lists dependencies. 

nodejs cpanel

 If you’re following our examples and would like to see Ensure Dependencies in action, add a file called package,json to the app’s directory with the following contents:

{
  "name": "nodejsapp",
  "version": "1.0.0",
  "description": "A Node App",
  "main": "app.js",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

As you can see, we have listed the Express web framework as a dependency.  The Ensure Dependencies button should now be available in Application Manager. When you click itcPanel installs Express and any applications and libraries it depends on. 

Adding Environment Variables to Your Node.JS App’s Environment

Environment variables are name-value pairs that store a chunk of information. They work much like variables in programming, except that they are not internal to the program but part of its external environment.  Servers use environment variables to hold useful configuration data. 

For example, CentOS uses the PATH environment variable to store a list of directories that contain command-line programs. When you enter a command like “ls,” the shell looks through those directories for an executable file with that name.  If there was no PATH variable, you’d have to enter the full path of every command:  “/usr/bin/ls” instead of just “ls.” 

The server administrator can change the PATH environment variable, controlling the directories the shell looks in without modifying its internal code.  With cPanel’s Application Manager, you can add environment variables to your Node.js app’s environment to configure its behavior in the same way. 

In our simple app.js file, this line of JavaScript tells the app the port it should listen for connections on. 

const port = 3000;

In reality, a developer is unlikely to know the correct port when they write the code.  To give users more flexibility, they could tell the app to look in its environment for a variable called PORT and to use its value when setting up the app. 

In Node.js, the JavaScript code looks something like this:

const PORT = process.env.PORT || 3000;

This sets the app’s internal PORT variable to the value of the environment variable called PORT or to a default of 3000 if an environment variable isn’t set. 

Now the user can tell the app which port to bind to by setting a PORT variable in the app’s environment. To do this in cPanel’s Application Manager, find the Environment Variables interface beneath Application Configuration and click Add Variable.

hosting marketers nodejs

Enter a variable name and value, and click Save. 

Editing Your Node.JS Application

You can edit a Node application’s registration configuration in the Application Manager.

Creating an Application in the cPanel Application Manager

Click the Edit link in the Actions column. In this interface, you can edit all the values you set when first registering your application, including the environment variables. 

Uninstalling Your Node.JS Application

To uninstall or “unregister ”a Node.js application from cPanel, click the unregister link at the right of the Application Manager table. 

When you unregister an application, cPanel removes it from the list, deletes its configuration file, and dissociates it from the domain. cPanel does not delete the application’s files, but you are free to delete them yourself in File Manager or on the command line. 

Bring Node.JS Hosting to Your cPanel Server

PHP remains the most widely used server language by a large margin, but Node.js, JavaScript, and web frameworks like Express, Meteor, and Nest are increasingly popular with web developers and tech-savvy users. cPanel and WHM’s Application Manager makes it easy for web hosts to support Node apps and JavaScript-focused users on their platform.

Deploy Node.js on our shared servers

Version Control with Git

Before we can configure your Node.js application, the first step is getting that application on your server. There are a few options. You can use FTP to upload the copy of your application to your server, or you can use cPanel’s native Git support to clone the repository onto your server and deploy from there. Either method meets the requirement to get the application onto the server. In this example, we’ll be using cPanel’s native Git support to clone the application onto your server and then deploy it.

Within the cPanel user account that you’d like to host the application on, under the “Files” tab, select the “Git Version Control” option. This will bring you to a page where you can create a Git repository. In this example, we’ll be using the chat example repository to deploy a simple chat application.

To keep your application data secure be sure not to clone or upload into the public_html folder since this makes the code itself potentially accessible from the web. CloudLinux strives to keep your data safe, and during deployment, it’s not a requirement that your application data be publicly accessible.

Here’s an example of the Git page, before the clone is completed.

git clone example

Once you click on “Create” this will bring you back to the repository page showing the full path of the application being deployed. This page is important, so save that path for later.

Application Configuration

With the application files in place on the server, we are ready to configure Node.js to launch that application from the web.  From cPanel on the same account under the “Software” tab, select “Setup Node.js App”. On this setup screen, you’ll select “Create Application” to bring up the options for choosing the Node.js version as well as whether to use a Development or Production environment.Notes on Choosing Development vs. Production:Development generally has different application hooks in the code of the application, depending on how this environment variable is set. As a general rule, Production is going to have more levels of caching, as well as minimal logging. So, for a Development environment set, you can expect the inverse, with fewer levels of application caching, and more verbose logging and error message output.

Example: In production, you may only see an error page, but in development, you may see a full stack trace on an application error, letting you know exactly where the error took place inside the code.

Here’s an example of an application that’s ready to be saved:

create node.js application

Node.js applications, in general, depend on several environment variables. These can be added by using the “Add Variable” button near the bottom right of the page. Your Node.js production or development variable is already set separately in the top section using the “Application Mode”, so it is not necessary to set it again in the Environment variables section.

This same menu is where you can select the version of Node.js that you’d like to use as well as the application’s startup file. This might be index.jsapp.js or any number of variations; it depends on the application.

Once you’ve saved your application, you’ll need to resolve its package dependencies.  The NPM package manager does this automatically based on the package.json file packaged with the application, so all that you’ll need to do here is click on the ‘NPM Install” button.  (This step will require your domain to resolve to an IP address, or the installation script will have an error) . NPM will read the contents of the package.json file and install the needed packages into a virtual environment specific to the application.

If you are familiar with the command line, you can follow the instructions at the top of the page to gain access to the “npm” and “node” commands to make additional changes manually, allowing for a great deal of customization: 

enter virtual environment command

Application Deployment

By this point, you’ll have your application configured and Node.js modules installed, so you’re ready to launch the application! CloudLinux makes this effortless: on the same page where you configured your application, click “Run JS Script”. This will execute the application startup file that you defined earlier during setup. As Node.js applications have several options, this can bring up another menu with different options to select depending on the application that you’re running. In general, you’ll want to select the “Start” option next. Finally, you can select the “Open” option to visit your page, and see your application!

CloudLinux’s Node.js Selector has many advantages over manual deployment.  It allows for several applications to be run under the same user, accessed under the “Setup Node.js App” page in your cPanel account. Phusion passenger is used for application handoffs, so you won’t need to set up any .htaccess redirects to tell the web server to forward to the applications port.  With Node.js Selector this is all handled for you.

How to fix “The media playback was aborted due to a corruption problem or because the media used features your browser did not support”

How to fix “The media playback was aborted due to a corruption problem or because the media used features your browser did not support”

Sometimes the player stops and you will see this error

"The media playback was aborted due to a corruption problem or because the media used features your browser did not support."

This could be to a number of causes

Browser issues

Poor Internet connection

Website plugins not supported by browser

Cached data in the system

The video file has a problem

Irrespective of the browser you’re using – Chrome, Mozilla Firefox, or Opera – try the below fixes first to resolve the issue:

Refresh your webpage
Try opening the page in another browser
Check your Internet connection
Delete cookies, cache and browsing history
Disable all plugins on your browser
Restart the browser

If none of the above quick fixes work, there may be some deeper issues with the video.

Copying the link of the stream to VLC I can see the direct m3u8 file is opening in VLC, however the error displayed in Google Chrome is:

ERROR: (CODE:3 MEDIA_ERR_DECODE) The media playback was aborted due to a corruption problem or because the media used features your browser did not support

I believe it is due to the Audio codec used on the stream, which VLC is showing as “ADTS”. Most browsers only support AAC or MP3 audio. You should check the media files streamed to ensure they have the correct format. I recommend reading this article on encoding your video files: How to Encode your Video Files Properly Before you Upload to the RTMP Server

What is rtmp server?

In the early days of streaming, we talking about 1990′ , the Real-Time Messaging Protocol (RTMP) was the de facto standard for transporting video over the internet (or in laymen’s terms, for streaming). RTMP is a TCP-based protocol designed to maintain persistent, low-latency connections — and by extension, smooth streaming experiences.

The protocol started out as live and on-demand streaming with Adobe Flash Player. Because this popular Flash plugin powered 90% of internet browsers in its popular days, RTMP was used ubiquitously. From live streaming to on-demand, to games and to live video chat.

The majority of encoders today can transmit RTMP, and most media servers can receive it. Even big social media players like Facebook, YouTube, Twitch, and Periscope accept it. However, RTMP streams run into compatibility issues when it comes to playback on popular browsers and devices. And by the end of this year 2020 most browsers will stop supporting it.

In this article, we’ll take a look at the RTMP specification, the history behind RTMP streaming, and alternative protocols to use.

What Is RTMP?
The RTMP specification is a streaming protocol initially designed for the transmission of audio, video, and other media data between a dedicated streaming server and the Adobe Flash Player. While once proprietary, RTMP is now an open specification, with a number of servers, or softwares like red5, wowza streaming engine, Nginx, and Adobe Media server.

The RTMP protocol has multiple variations:

  • RTMP proper, the “plain” protocol which works on top of TCP and uses port number 1935 by default.
  • RTMPS, which is RTMP over a TLS/SSL connection.
  • RTMPE, which is RTMP encrypted using Adobe’s own security mechanism. While the details of the implementation are proprietary, the mechanism uses industry standard cryptographic primitives.[1]
  • RTMPT, which is encapsulated within HTTP requests to traverse firewalls. RTMPT is frequently found utilizing cleartext requests on TCP ports 80 and 443 to bypass most corporate traffic filtering. The encapsulated session may carry plain RTMP, RTMPS, or RTMPE packets within.
  • RTMFP, which is RTMP over UDP instead of TCP, replacing RTMP Chunk Stream. The Secure Real-Time Media Flow Protocol suite has been developed by Adobe Systems and enables end‐users to connect and communicate directly with each other (P2P).
  • While the primary motivation for RTMP was to be a protocol for playing Flash video, it is also used in some other applications, such as the Adobe LiveCycle Data Services ES.

I suggest that you order our free demo rtmp account at our site.

What is rtmp server

How to make a rtmp server?

The best 3 ways to make a RTMP server.

First what is a RTMP server and even before that what is RTMP?

RTMP (Real-Time Messaging Protocol) is an application-level protocol owned by Adobe. It was originally designed for delivering on-demand media and live media (i.e live audio, video, and data) over the Internet between a Flash player and RTMP Media Server. For example we have the HTMP protocol, that is the sites which you can see on the browser, so the HTMP protocol is for website. While the RTMP is for media, it allows media files, like video, audio, images which can be easily be transferred or streamed by other users.

So the a rtmp server is a normal server, or a vps, which has a rtmp software which can then be used to transfer this media files.

Now the important thing on all this is what is this software? And the main softwares that create the RTMP are

1- Flash Media Server, now changed to Adobe Media Server.

2- Red5

3- Wowza, now called, Live Streaming Engine.

And these are the 3 main RTMP servers or softwares, there are other like Nginx, but not so well known and not really used for production purposes.

How it all started, the RTMP?

It started with Adobe, they the ones who created this software with flash media server, it is a high quality software and it is very expensive, $4500 for the license.

But we must explain the issues with the RTMP, it is very popular some years ago, 2010 and about, every one wanted to make video chats, the problem is that flash is going to be disabled at the end of this year 2020 and video chats with flash will stop working.

But the RTMP has one incredible advantage, it is very fast between servers, a delay of 1 or 2 seconds of latency.

So RTMP will not go out soon because we can use for live streaming from the broadcaster to the server, using the RTMP and then on the server it is distributed on an.y device using instead of RTMP using HLS, which means HTTP Live Streaming.

The latency now is 20-25 seconds, so it cannot be used for video chats but is perfectly alright for live streaming and ondemand video streaming

Then we have Red5, which now has two versions the paid version called Red5 Pro and it is also expensive, difficult to manage but can be used for live streaming and for video chats.

Hosting Marketers uses the free open source software on all our servers, and it was the first shared hosting offering this service.

It is still used on some video chats but not sure what will happen after 2020….

You can read more about red5 on our old blog post “What is the use of Red5

Then we have Wowza, which is the one we mostly use on our RTMP servers, it is very stable, easy to manage and very high quality.

There are many reasons for using Wowza to provide HLS streaming services compared to a generic web server. You’ve essentially listed them yourself, though to provide a few specifics; Wowza’s HLS implementation includes robust DRM functionality, timed data events via ID3 tags, alternative audio tracks. More are listed here.

I would recommend reading our Quick Start Guide which covers the concepts involved. For more detail around the HLS capabilities I’d suggest you try our rtmp free trial account, on our site.

Church Live Streaming

We also use it for live streaming on sports and Church services with live streaming, we adjust the server to reduce the latency, wecan reduce to 5-6 seconds by making some adjustments.

iglesia en vivo | Cómo transmitir en vivo el servicio de tu iglesia: una guía práctica.

La propagación del Coronavirus (COVID-19) ha obligado a que las iglesias latinoamericanas cancelen la mayoría de sus reuniones y se pregunten cómo compartir la enseñanza bíblica usando la tecnología. Pero la transmisión Iglesia en vivo de un sermón o servicio dominical puede ser un desafío desalentador. Si perteneces a una iglesia que carece de los recursos para una transmisión, puedes usar esta guía práctica sobre lo que necesitas saber y tener para hacerla.

¿Qué plataforma debemos usar?
Las dos opciones más populares para la transmisión de videos en vivo son: Facebook y YouTube. Consideremos los beneficios y desafíos que nos ofrece cada una.

Facebook. Quizá sea el medio más fácil y accesible para una transmisión en vivo, pues la mayoría de iglesias ya tienen una cuenta. Sin embargo, hay al menos una desventaja notable, y es que el contenido que graben o transmitan desde esta plataforma permanecerá dentro de Facebook, y es difícil compartirlo por otros medios.

iglesia en vivo

A pesar de este desafío, Facebook Live puede tener sentido para tu iglesia, dependiendo de su presencia en esta red social, y de cómo desean manejar los videos una vez haya terminado la transmisión.

Te recomendamos hacer una prueba con la configuración en “privado”, de modo que puedas explorar la interfaz antes de hacer una transmisión pública por primera vez. Aquí encontrarás una guía paso a paso sobre cómo transmitir en vivo desde Facebook.

Youtube. Para transmitir en vivo desde esta plataforma necesitarás crear una cuenta para tu iglesia, la cual debe estar vinculada a una cuenta de Google. Si tu iglesia no tiene un canal de Youtube, aquí encontrarás una guía paso a paso para crearlo.

Una de las grandes ventajas de usar esta plataforma es la facilidad de compartir la transmisión y usar el contenido en otras plataformas como Facebook o la página web de la iglesia. Aquí encontrarás una guía paso a paso sobre cómo transmitir Iglesia en vivo desde Youtube.

Aunque existe una variedad de alternativas a Facebook y YouTube, incluso algunas creadas específicamente para iglesias, estas pueden resultar menos útiles por ser servicios pagados o tener menos soporte técnico.

Las mejores prácticas para la transmisión de los servicios dominicales
Cuando hayas elegido la plataforma para transmitir en vivo, debes considerar el orden y los elementos del servicio que vas a incluir. Aquí hay algunas preguntas comunes que te ayudarán a decidirlo.

  1. ¿Deberíamos transmitir un servicio completo o solo la predicación?

Primero, investiga si en tu país existen regulaciones sobre el uso de la música cristiana en eventos públicos o transmisiones en vivo. Usualmente las regulaciones sobre los derechos de autor son bastante complejas, y varían de lugar a lugar. Por eso, para evitar complicaciones de este tipo, te recomendamos omitir la parte musical del servicio en línea si representará un obstáculo mayor.

Segundo, evalúa si tienes el equipo y condiciones necesarias para transmitir la música en vivo. La experiencia de cantar junto a la iglesia los domingos es muy diferente a una transmisión en línea, y debes saber que la calidad de la producción musical podría distraer en lugar de edificar e invitar a la adoración.

Finalmente, selecciona la información que vas a compartir, como anuncios o instrucciones, puesto que una transmisión en línea llega a una audiencia mayor, y no solo a la membresía local.

  1. ¿Cómo debemos colocar la cámara, interactuar, y preparar el escenario?

La ubicación de la cámara se verá mejor cuando el ángulo está al nivel de los ojos del predicador. En un escenario ideal de transmisión en vivo, el pastor estará hablando directamente a la cámara, haciendo contacto visual con los espectadores del video. La iluminación simple en forma de lámparas, una luz de anillo o un kit de iluminación básico, pueden ser de gran ayuda para mejorar el video, dependiendo de la interacción del predicador con la cámara.

También es importante que el predicador evite el uso de camisas de color blanco, rojo o con estampados pequeños ya que estos factores pueden ocasionar problemas de visibilidad a la hora de la transmisión. Los colores pastel y sólidos, sin estampados, son adecuados para estos casos.

  1. ¿Qué tecnología debemos usar?

Cuando hablamos de equipos de grabación de video, hay algunas cosas básicas a considerar según tu presupuesto y las habilidades de tu equipo de colaboradores.

Nivel 1: Grabar con un teléfono celular. La fortaleza de este método está en su portabilidad y costo. Es prácticamente gratuito, a menos que desees reforzarlo con un soporte para el teléfono y un micrófono para mejorar el audio. La limitante de esta opción está en la calidad de la cámara y el audio del dispositivo.

Nivel 2: Grabar con una cámara dedicada. El equipo más usado para esta función es la cámara Mevo. Su costo oscila entre los 500 a 1000 dólares y proporciona una excelente solución para una transmisión en vivo. Supera la calidad de un teléfono móvil, conserva parte de la informalidad de la plataforma, y proporciona una solución de video de punto fijo razonable. Con esta opción podrás transmitir tanto en Facebook como en YouTube al mismo tiempo.

Nivel 3: Grabar con Boxcast. Por 100 dólares mensuales obtienes el hardware y el software necesarios para transmitir tu servicio en la web. También necesitarás invertir en cámaras capaces de capturar videos en alta calidad (HD), con un costo entre los 500 y 1000 dólares por cámara, así como un micrófono y amplificación de alta calidad (probablemente funcione uno que tu iglesia ya usa).

Otras soluciones de software para computadoras como Restream y OBS (este último es gratuito y con muchas herramientas), pueden lograr algunos de los resultados de Boxcast, pero requerirán un poco más de experiencia y conocimiento técnico.

El nivel apropiado para tu iglesia
Para tomar una decisión sobre cuál nivel es el apropiado para tu iglesia, considera los siguientes factores:

Presupuesto: El nivel 1 costará entre 0 y 50 dólares. El nivel 2 está entre 500 y 1000 dólares. Y el nivel 3 requiere una inversión de 1200 dólares por año, con costos iniciales de alrededor de 1000 dólares.

Colaboradores: Habla con el equipo de colaboradores para determinar con qué instrumentos y plataforma se sienten más cómodos o qué experiencia han tenido usando alguna de estas opciones. Al mismo tiempo, ten cuidado de no comprometerte con métodos complejos de hardware, software, o transmisión que no funcionarán a menos que un solo miembro del equipo pueda ejecutarlos.

Visión: Aunque tu Iglesia en vivo haga un compromiso temporal con la transmisión en vivo, la planificación inteligente de inversión durante este tiempo puede generar dividendos para el ministerio en el futuro. Por lo tanto, asegúrate de que las compras que realicen o los métodos que prueben les sirvan a largo plazo.

Piensa en el uso y aprovechamiento futuro de esta tecnología si deciden continuar transmitiendo los servicios en vivo o si empiezan a producir otros recursos para la edificación de la iglesia.

Comienza con poco y empieza a crecer
Cuando se trata de transmisión en vivo, la recomendación es comenzar con poco y crecer con el tiempo. No te decepciones si tu primer intento es un desastre, pero asegúrate de informarte, toma nota de los comentarios, examina los análisis, y haz que el próximo intento sea un éxito.

Busca las maneras de mejorar mientras ayudas a otras iglesias a crecer en sus capacidades también. Oramos que en esta época de limitaciones para reunirnos, el Señor nos permita optimizar el uso de la tecnología para la edificación de la iglesia y la gloria de su nombre.

Iglesia en vivo