Lesson 34. Deploying your application

At this stage, you’ve completed a few iterations of your application, and it’s time to make it available to the World Wide Web. This lesson introduces application deployment with Heroku. First, you set up your application to work with Heroku’s services and plugins. In a few easy steps, you’ll have your application live, with a unique URL that you can share with your friends. Next, you see how to set up your MongoDB database and populate your application with content. Last, you learn about tools you can use with Heroku to monitor your application in production, as well as guidelines for making future changes in your production code and Heroku plugins worth exploring further.

This lesson covers

  • Configuring a Node.js application for Heroku
  • Deploying a Node.js application
  • Setting up a remote MongoDB database
Consider this

You’ve spent countless hours adding features and functionality to your application, only to have it run locally on your personal computer. It’s about time that you expose your work on the recipe application to the public. The final step in the development process is deployment. In this lesson, I discuss the necessary steps to get your application ready for production.

34.1. Preparing for deployment

Deployment is the process of taking your application code from your development environment and publishing and running it on the internet to make it accessible to the public. Until this point, you’ve been developing your application in a local environment. Developers would refer to the application running at http://localhost:3000 as running in your development environment.

One option is to set up a new environment. You need to re-create the system settings and resources that made it possible to run your application on your own machine: a physical computer with Node.js installed, the ability to install any external packages, and a JavaScript engine to run the application. There’s no escaping the fact that your application depends on physical hardware to function. For this reason, deploying your application to a production environment, somewhere accessible to others online, requires some machine or service to run your application.

You could set up your own computer to run your application and configure your home network to permit users to reach your application via your home’s external IP address. The configuration steps are a bit involved, though; they might pose security threats to your home internet network; and they’re beyond the scope of this book. Also, if your computer shut down, your application would be unreachable.

The popular alternative is to use one of many cloud services to host and run your application. These services often come at a cost, but for demonstration purposes, you can deploy your application through Heroku’s free account services. Heroku is a cloud-based platform that offers servers—the physical processing computers and memory—to run your application. What’s more, these computers often come prepackaged with the installation of Node.js that you need and require very little setup on the developer’s part.

To get started with deployment, ensure that you have the Heroku command-line interface installed by running heroku --version in terminal (heroku version in the Windows command line). Also make sure that you have Git installed by running git --version. If you see some version of these tools printed on the screen, you can continue to the deployment steps.

Note

If you haven’t yet created your Heroku account, set up the command-line interface (CLI), or installed Git, please follow the instructions in lesson 2.

Before you can deploy to Heroku, you need to make a couple of changes to your application to make it compatible with the services that Heroku provides. Heroku will run your application by using the application’s PORT environment variable, so you need to have your application ready to listen at both ports, as shown in the next listing. In this code, you create a constant, port, and assign it to the PORT environmental variable, if it exists. Otherwise, the port defaults to 3000. This port number should remain the same as in previous lessons.

Listing 34.1. Changing the application’s port in main.js
app.set("port", process.env.PORT || 3000);               1
const server = app.listen(app.get("port"), () => {       2
  console.log(`Server running at http://localhost:
${app.get("port")}`);
});

  • 1 Assign the port constant.
  • 2 Listen at the port assigned to port.

Similar to the way that Heroku specifies the application’s port, the database you’ll use also can be defined in an environmental variable. In main.js, change the database connection line to mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost:27017/recipe_db", {useNewUrlParser: true}). This line tells Mongoose to connect to the database defined in MONGODB_URI or to default to your local recipe_db database location. (See section 3 for details on why this environmental variable exists.)

Last, create a new file called Procfile at the application’s root. This file has no extensions or suffix, and its name is case-sensitive. Heroku uses this file to find out how to launch your application. Add web: node main.js to this file. This single line tells Heroku to create a new server, called a dyno, intended for web interaction, and to use node main.js to start the application.

With these three changes in place, you can finally deploy the application.

Quick check 34.1

Q1:

Why do you need the Procfile in your project folder?

QC 34.1 answer

1:

Heroku uses the Procfile as a configuration file to start your application.

 

34.2. Deploying your application

With the appropriate configurations in place, you can use Git and the Heroku CLI to deploy your application. Throughout this book, you haven’t used Git for version control. Although versioning your code isn’t necessary in your development environment, it’s good practice, and in the case of deployment, it’s required to get your application to its production environment on Heroku. If you’re using Git for the first time, go to your project’s root directory in terminal, and initialize the project with Git by running git init. In the next step, you add the files that you want in your Git repo, but you don’t want some files in this repo.

You may recall that the node_modules folder gets created when you run npm install. This folder can get pretty large, and adding it to your Git repo isn’t recommended. To ignore this folder, create a new file called .gitignore at the root of your application directory. Add /node_modules to that file in your text editor, and save. That’s all you need to do for Git to know not to add those files within this folder.

To bundle your application code into a specific version, add the rest of the application’s files to Git’s staging level by running git add . (including the period). Then run the command git commit -m "Initial application commit" to save and commit this version of your code and receive a feedback message.

Note

Any other changes you make that aren’t added and committed following the same process won’t appear in your production environment.

With your code in version control, you can use the heroku keyword in terminal to initiate a new application for deployment. Run the command heroku create in your project directory in terminal to generate a new URL for your project. The response detailing the name of your Heroku application, its URL, and Git repository should resemble the following listing. This command also creates a connection to Heroku’s remote Git repository for your code. You can run the command git remote -v to reveal the URL to that repository.

Listing 34.2. Creating a new Heroku app
Creating app... done,   crazy-lion-1990             1
https://crazy-lion-1990.herokuapp.com/ |
https://git.heroku.com/crazy-lion-1990.git

  • 1 Display the results of creating a new Heroku app.

Next, push your latest versioned code from your computer to the Heroku repository you set up. Publishing your code is the same as uploading your code to a server that will host your application on the internet. You can publish by running the command git push heroku master. This step is the most important part of the process because it’s where all your code gets uploaded and published on Heroku’s services. This step is also when Heroku runs npm install to download all your application’s package dependencies.

This process may take about a minute, depending on your internet connection. If you experience any issue or notice an error in the process, make sure that you can still run your application locally before trying again.

If your application didn’t depend on a database, you could go directly to the URL provided after the heroku create command in your browser. If you try visiting your application’s /courses URL, you may see an error page (figure 34.1). Because your home page doesn’t depend on any persistent data, however, that page should load without any errors.

Figure 34.1. Displaying the Heroku error page

Note

If you still have remnants of the bcrypt package in your project, you might run into issues with deployment to heroku depending on your version of Node.js. Try unninstalling bcrypt and replacing it with bcrypt-nodejs in usersController.js. In terminal you’ll need to run npm uninstall bcrypt && npm i bcrypt-nodejs -S.

This error likely has to do with the fact that you haven’t set up your database yet. You can verify, though, by running the command heroku logs --tail in your project’s terminal window. This command provides a live feed of logs from the application online. You’ll find a lot of messages here, and it’s the first place I recommend checking if you experience any issue with your application in the future. Suppose that you see an error for a missing database. You can fix the problem by connecting to a MongoDB database.

Note

If you need some assistance with your Heroku CLI commands, run the command -heroku help in terminal or visit https://devcenter.heroku.com/articles/heroku-cli--commands.

Quick check 34.2

Q1:

What does the heroku create command do?

QC 34.2 answer

1:

heroku create registers a new application name and code repository for your application on Heroku’s services. It also links your local Git repository to the remote repository by the name of heroku.

 

34.3. Setting up your database in production

Because you don’t have direct access to the server on which your production application is running, you can’t download, install, and run a MongoDB database on the same server, as you do in development. Heroku provides a free plugin, however, that you can use to set up a small MongoDB database. To add this plugin from terminal, run the command heroku addons:create mongolab:sandbox. This line provisions a sandbox database from MongoLab (mLab).

With the help of other cloud services such as Amazon and Google, mLab provides databases and MongoDB servers that can be accessed remotely via a URL. The URL you get is added to your application as the environmental variable MONGODB_URI. This variable means that your application can use the variable MONGODB_URI to get the URL of the database.

Warning

The URL provided by mLab is a direct link to your application’s data. Only your application on Heroku should use this URL; otherwise, you risk database-security vulnerabilities.

You previously set up your application to use this variable. You can verify that it exists in your application by running the heroku config command in terminal. The result of running this command is a list of configuration variables used by the application. You should see only one variable for your database at this time.

Note

You can add new environmental variables by running the command heroku config:set NAME=VALUE, where Name is the name of the variable you want to set and VALUE is its value. I might set heroku config:set [email protected].

After a few minutes, your application should be ready to view. In your web browser, visit the URL provided earlier by Heroku, and add the /courses path to see an empty table, as shown in figure 34.2. You should see the home page of your application. Try creating new user accounts, subscribers, and groups through the forms you created in past lessons.

Figure 34.2. Displaying the Heroku courses page

You may be wondering whether there’s an easier way to populate your new database online with data than manually entering information in the browser forms. There is! I show you that technique, and some other tools and tips, in lesson 35.

Quick check 34.3

Q1:

How do you view and set environmental variables on your Heroku application?

QC 34.3 answer

1:

To view environmental variables on your Heroku application, run heroku config in your project’s terminal window. You can set new variables by using heroku config:set.

 

Summary

In this lesson, you learned about preparing your application for production and deploying it to Heroku. First, you changed some application configurations to help your Heroku dyno handle and run your application. Next, you deployed the application through your terminal Heroku CLI. Last, you set up a remote MongoDB database by using the mLab plugin through Heroku. In lesson 35, you discover how to manage your application in production, add data, and debug problems.

Try this

With your application on Heroku, test all the functionality to make sure that it works. Everything may seem to work as intended at first, but keep in mind that the environment is different, and sometimes your code may not work as expected. Try opening one terminal window with heroku logs --tail running alongside a browser window with your production application, and watch the log messages that Heroku prints.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset