If you follow this simple two-part tutorial to the letter, you will be able to make an application using Node.js with Heroku, in a matter of minutes.
In this tutorial we are assuming that you have a free Heroku account, and that you also have Node.js with npm installed.
The tutorial assumes that you have a free Heroku account, and that you have Node.js and npm installed locally.
Prepare the application
In this step, you will prepare a sample application that will be ready to be deployed on Heroku. If you are somewhat confused, or confused, you may want to check out our first introductory articles: Controlling Node.js Security Risk from npm Dependencies, or Node Hero - Node.js Authentication using Passport.js
First steps
In the first step, you are going to install a Heroku command line interface (CLI). We normally use the CLI to manage and scale the applications, and also to run the application locally. You have to download, install, and run the installer for your daily operating system.
- On Mac OS: Para que descargues el instalador de paquetes en tu equipo con Mac OS, da click aquí: Download installer for Mac OS.
Although you also have it available from your Homebrew:$ brew install heroku / brew / heroku
- On Windows: So that you can download the package installer on your Windows computer, click on one of these two as needed.
- Ubuntu 16+: Ahora, si tu caso es que utilizas un software libre en tu PC, ejecuta este código en tu terminal.
$ sudo snap install heroku --classic
Already installed installed, you can use the command heroku
from command shell. In Windows, you must start the command prompt (cmd.exe) or Powershell to access the shell command. Log in with the email address and password you used to create your Heroku account:
heroku login Enter your Heroku credentials. Email: email [email protected] Password: *****
Authentication is required to allow both login commands to work heroku
as the commands of git
. Before you continue, make sure you have the prerequisites for this installed correctly. Type each command below and make sure it shows the version you have installed. (Keep in mind that your versions could be different from the example). If it does not return any version, but return to the introduction of this tutorial and install the prerequisites. The following locale is required to complete the "Application dependencies" and subsequent steps. Remember that this tutorial will work for any Node version higher than 8; now verify that you have the requirements installed:
Try the Node version
node --version v8.11.1
Note that npm it is installed with Node.js, so check that it is installed. If you don't have it, install a newer version of Node:
npm --version 5.6.0
Now check that you have installed git. If it is not, install it and try again.
git --version git version 2.15.1
Preparing your application
In this step, you will begin to prepare a sample application that is ready to be implemented in Heroku. In order to make your own copy of the application we are developing, execute the following commands in your command terminal or local terminal:
git clone https://github.com/heroku/node-js-getting-started.git cd node-js-getting-started
You now have a working Git repository that contains a simple application as well as a file package.json, which is used by Node's dependency manager.
Deploying your application
En este paso desplegarás la aplicación a Heroku. Cree una aplicación en Heroku, que prepara a Heroku para recibir su source code.
$ heroku create Creating sharp-rain-871 ... done, stack is cedar-14 http://sharp-rain-871.herokuapp.com/ | https://git.heroku.com/sharp-rain-871.git Git remote heroku added
When you create an app, heroku also creates a remote git (called) and associates it with your local git repository. Heroku generates a random name (in this case sharp-rain-871) for your application, or you can pass a parameter to specify your own application name. Now display your code:
$ git push heroku master Counting objects: 488, done. Delta compression using up to 8 threads. Compressing objects: 100% (367/367), done. Writing objects: 100% (488/488), 231.85 KiB | 115.92 MiB / s, done. Total 488 (delta 86), reused 488 (delta 86) remote: Compressing source files ... done. remote: Building source: remote: remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL = error remote: NODE_VERBOSE = false remote: NODE_ENV = production remote: NODE_MODULES_CACHE = true remote: remote: -----> Installing binaries remote: engines.node (package.json): 8.11.1 remote: engines.npm (package.json): unspecified (use default) remote: remote : Resolving node version 8.11.1 ... remote: Downloading and installing node 8.11.1 ... remote: Using default npm version: 5.6.0 .... remote: -----> Build succeeded! remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing ... remote: Done: 19M remote: -----> Launching ... remote: Released v3 remote: http://sharp-rain-871.herokuapp.com deployed to Heroku remote: remote: Verifying deploy ... done. To https://git.heroku.com/nameless-savannah-4829.git * [new branch] master -> master
The application is now deployed. Make sure at least one instance of the application is running:
$ heroku ps: scale web = 1
Ahora visita la aplicación en la Url generada por su nombre de aplicación. Como un atajo práctico, puede abrir el sitio Web de la siguiente manera:
$ heroku open
Viewing the records
Heroku trata los registros como flujos de eventos ordenados por tiempo agregados de los flujos de salida de todas sus aplicaciones y componentes Heroku, proporcionando un solo channel para todos los eventos. Ver información sobre su aplicación en ejecución usando uno de los comandos de registro , heroku logs –tail:
heroku logs --tail 2011-03-10T10:22:30-08:00 heroku[web.1]: State changed from created to starting 2011-03-10T10:22:32-08:00 heroku[web.1]: Running process with command: `node index.js` 2011-03-10T10:22:33-08:00 heroku[web.1]: Listening on 18320 2011-03-10T10:22:34-08:00 heroku[web.1]: State changed from starting to up
Visite su aplicación en el browser nuevamente, y verá otro mensaje de registro generado. Presione Control+Cpara detener la transmisión de los registros.
Defining a Procfile
Use un Procfile , un archivo de texto en el root directory de su aplicación, para declarar explícitamente qué comando debe ejecutarse para iniciar su aplicación. La aplicación Procfile de ejemplo que implementó se ve así: web: node index.js
Esto declara un solo tipo de proceso weby el comando necesario para ejecutarlo. El nombre webes importante aquí. Declara que este tipo de proceso se adjuntará a la pila de enrutamiento HTTP de Heroku y recibirá traffic web cuando se implemente. Procfiles puede contener tipos de proceso adicionales. Por ejemplo, puede declarar uno para un proceso de trabajo en segundo plano que procesa elementos fuera de una cola.
Scaling the application
Right now, your application is running on a single benchmark band. Think of a dynamometer as a lightweight container that runs the command specified in the Procfile file. You can check how many dynos are running using the ps command:
$ heroku ps === web (Free): `node index.js` web.1: up 2014/04/25 16:26:38 (~ 1s ago)
By default, your app is deployed to a free dynamometer. Free dinosaurs will sleep after half an hour of inactivity (if they don't get any traffic). This causes a delay of a few seconds for the first request upon waking up. Subsequent requests will be made normally. The free dynamics also consume a monthly quota at the account level of free dynamization hours, as long as the quota is not exhausted, all free applications can continue to run. To prevent Dyno from sleeping, you can upgrade to a hobby or professional dino type as described in the Dyno Types article. For example, if you migrate your application to a professional dynamometer, you can easily scale it by running a command that tells Heroku to run a specific number of triggers, each executing its own type of web process. Scaling an application on Heroku is equivalent to changing the number of dynos that are running. Scale the number of web dynos to zero:
$ heroku ps: scale web = 0
Access the application again by pressing update in the web tab, or heroku open to open it in a web tab. You will receive an error message because you no longer have any web diagnostics available to service requests. Scale again:
$ heroku ps: scale web = 1
For abuse prevention, scaling a non-free app to more than one dynamo requires account verification. To continue with the lesson, continue to our next post ➡ How to implement Node.js with Heroku or Docker? Part 2