Deploying to Production (Heroku and Git)
We're going to learn how to deploy our application onto Heroku, a platform to host your web apps, and have it be accessible by anyone, anywhere in the world. We'll walk through all the installation instructions required for you to be able to easily run your web application on Heroku and easily push updates.
What is Heroku?
Heroku is a cloud platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.
Heroku is easy to set up and offers a free account so that you can follow along and deploy your URL Shortener (or any other) application. You only need to pay if your app starts getting a lot of traffic. First, we will need to set up Git, a version control system, for our codebase. This will allow us to easily integrate with Heroku.
Let's dive right into it!
Installing Git
Git is a version control system (VCS) that tracks changes to files over time. It maintains a history of every version of your code, allowing you to revisit specific versions whenever you'd like. It also provides many other advanced options which are very useful in managing our projects.
Heroku uses git for its deployments, so let's go ahead and install it.
Windows
The most official build is available for download on the Git website. Just go to http://git-scm.com/download/win and the download will start automatically.
Run the installer you just downloaded. You can select next on all steps except for the one titled Adjusting your PATH environment. On that step, select the bottom option of Use Git and optional Unix tools from the Windows Command Prompt.
Everything else can remain as the default setting.
Don't forget to restart the command prompt or powershell after the installation has finished successfully.
OS X
Download Git from here and follow the instructions.
Note: If you are running OS X 10.6-10.8, you will need to install<a href = https://sourceforge.net/projects/git-osx-installer/files/git-2.3.5-intel-universal-snow-leopard.dmg/download target="_blank"> this version of git.
Debian or Ubuntu
$ sudo apt install git
Fedora
$ sudo dnf install git
openSUSE
$ sudo zypper install git
Starting our Git repository and Committing
Git tracks changes to a particular set of files in what's called a code repository (or "repo" for short). Open up your console and set the initial configuration as follows:
$ git config --global user.name "Your Name"$ git config --global user.email you@example.com
This is a one-time configuration. You won't have to re-enter the username and email ever again. Let's start initializing repo with one for our project. Navigate to your project directory on your console.
Note: Check your current working directory with a pwd (Mac OS X/Linux) or cd (Windows) command before initializing the repository. You should be in the URL_Shortener folder.
Run the following command to initialize your git repository:
$ git initInitialized empty Git repository in ~/URL_Shortener/.git/
Initializing the git repository is something we need to do only once per project.
Git will track changes to all the files and folders in this directory, but there are some files we want it to ignore. We do this by creating a file called .gitignore in the base directory. You may need to do this in projects of other technologies but not in Meteor projects. If you check your base directory, Meteor has created this file with required contents.
It's a good idea to use a git status command before git add or whenever you find yourself unsure of what has changed. This will help prevent any surprises from happening, such as wrong files being added or committed. The git status command returns information about any untracked/modified/staged files, the branch status, and much more.
After adding the files, we need to commit the changes to store them permanently into the git repository. When we commit the changes, a commit object is created into the git repository which uniquely identifies a new revision of the contents of the repository.
Let's commit our URL Shortener project we have so far. Make sure you're at the root directory URL_Shortener/
Go to your console and run these commands:
$ git add -A$ git commit -m "My URL Shortener App, first commit"
git add -A tells git to stage all the changed files in our working directory. Staging a file means marking it as “ready” for the commit. git commit stores these current changes in a new commit with a message describing the change (denoted by -m). You can check the commits log using the command $ git log for detailed logs or $ git log --oneline for brief information.
Create a Heroku Account
To start using Heroku, we first need to create a free Heroku account. Go to their Sign up page and follow the instructions to create your account. Remember your email and password as you'll need it to set up the CLI next.
Install Heroku Command Line Interface (CLI)
We will install Heroku toolbelt which provides a CLI(Command Line Interface) to manage our apps easily. Install Heroku CLI from here. Use the instructions above to see if you should use the 64-bit or 32-bit installer.
Windows
Click on the Download the installer under Windows
Mac
Click on the Download the installer under macOS.
Ubuntu / Debian
Run the following from your terminal:
$ curl https://cli-assets.heroku.com/install-ubuntu.sh | sh
Create an App on Heroku
Once installed, login to Heroku through command line interface by typing the command:
$ heroku login
Enter the login credentials you created while signing up and you will be logged in from your terminal/command prompt. You will see a message Logged in as your_email once you are logged in.
Let’s create an app using command line interface:
$ heroku create shorten-link
Here, shorten-link is the name of the app that Heroku will create. The app name should be unique globally. If the name is not unique, Heroku will give an error that Name is already taken by a user. In this case, try the command again with some other name.
Also, note that https://test-shorten-link.herokuapp.com is the deployment URL provided by Heroku server which is same as your app name with heroku domain. In case, you have your own custom domain, you can use it by configuring the name servers from the settings.
https://git.heroku.com/test-shorten-link.git is the remote location where we need to push the project files. Heroku already added the remote for us which can be checked by typing the command:
$ git remote -v
Updating URL_Shortener with Server URL
This step is required only if you are deploying the URL_Shortener application we created in the last assignment. If you remember, when we displayed the short URLs in link_list.js, we gave the URL format as `http://localhost:3000/${token}`
We need to update it with new URL for the application to work properly because we are not using localhost now. Let’s update the file as:
imports/ui/components/link_list.js
import React, {Component} from 'react';import { withTracker } from 'meteor/react-meteor-data';import { Links } from '../../api/links';import { Meteor } from 'meteor/meteor';class LinkList extends Component{renderRows(){return this.props.links.map(link =>{const {url, clicks, token} = link;const shortLink = `http://test-shorten-link.herokuapp.com/${token}`;//Updated the above URL formatreturn(<tr key={token}><td>{url}</td><td><a href={shortLink} target="_blank">{shortLink}</a></td><td>{clicks}</td></tr>)})}render(){return(<table className="table"><thead><tr><th>URL</th><th>Address</th><th>Clicks</th></tr></thead><tbody>{this.renderRows()}</tbody></table>);}}export default withTracker(()=>{Meteor.subscribe('links');return {links: Links.find({}).fetch()};}) (LinkList);
Since we have made changes in our files, let’s commit it as follows:
$ git add -A$ git commit -m "Updated the short-URL format"
Configuring Heroku for Meteor Applications
For now, you can test the app URL which will look like this.
We need to set up the server now. Setting up Meteor project on Heroku is simple but it is different from other Node.js apps (if you have used Heroku before). Heroku doesn’t support Meteor by default but it supports Node.js . Hence, we need to use a Heroku buildpack which will configure and install Meteor on Heroku for us. The buildpack we are going to use is meteor-buildpack-horse
We will make Heroku to set the buildpack to be used the next time the app is deployed. We can set the buildpack as:
$ heroku buildpacks:set https://github.com/AdmitHub/meteor-buildpack-horse.git
With this buildpack, the next time our app is deployed, Heroku will install Meteor and start the server.
The next step is to give the Node.js version our project is using. This is important for installation of Meteor on the server. We can know our node version using the command:
$ meteor node –v
We need to take note of it (here, mine is 8.11.3, may differ in others) and add it in our package.json file with the key as engines as:
"engines":{"node":"8.11.3"},
Finally, our package.json looks like:
package.json
{"name": "URL_Shortener","private": true,"scripts": {"start": "meteor run","test": "meteor test --once --driver-package meteortesting:mocha","test-app": "TEST_WATCH=1 meteor test --full-app --driver-package meteortesting:mocha","visualize": "meteor --production --extra-packages bundle-visualizer"},"dependencies": {"@babel/runtime": "^7.0.0-beta.51","connect-route": "^0.1.5","meteor-node-stubs": "^0.4.1","react": "^16.4.1","react-addons-pure-render-mixin": "^15.6.2","react-dom": "^16.4.1","valid-url": "^1.0.9"},"engines":{"node":"8.11.3"},"meteor": {"mainModule": {"client": "client/main.js","server": "server/main.js"},"testModule": "tests/main.js"}}
Now that we have made changes in our files, let’s immediately commit it as:
$ git add -A$ git commit -m "Added node version to engines"
Integrating MongoDB Database and Adding Environment Variables
The next step for Meteor deployment is to set up a MongoDB database. To do this, we are going to use a Heroku add-on. Heroku add-ons give access to extra functionalities we may need for our project. We can explore the different add-ons available here. If you go through the add-ons list, you may find mLab MongoDB. We will install this add-on for our database because it provides free storage of 500 MB as a part of Sandbox plan. There are other paid plans provided by mLab which you can find on this page. You can explore other add-ons and their paid or free packages if your application starts getting heavy traffic.
We can install the add-on as:
$ heroku addons:create mongolab:sandbox
This command will install the MongoDB database and display an Environment variable MONGODB_URI
This environment variable actually stores the address of database server to which our application is mapped to. You can view all your environment variables using the command:
$ heroku config
If you find MONGODB_URI variable, everything’s good. The buildpack we installed knows how to use this variable.
Note: Heroku asks the users to verify their account by entering the credit card details before installing any add-on. They ask the card information to verify the user and they won’t charge unless you buy a paid service/add-on. However, if you do not want to give your credit card information for any reason, there is a hacky way to use mLab’s database which is discussed in the next section.
Another Environment variable we need to set up is the root URL which is required by Meteor to set the routing for your application. To set this Environment variable, copy your project URL and set it as:
$ heroku config:set ROOT_URL="https://test-shorten-link.herokuapp.com"
Make sure you do not have trailing ‘/’ at the end of URL.
You can also set Environment variables through Heroku website by navigating to the Config Vars option under Settings tab of your application.
You can re-run $ heroku config to make sure if environment variable is created.
Everything is set up now. The last step is to push your code to Heroku.
$ git push heroku master
Since we are pushing the code on Heroku for the first time, it will install Meteor and all the dependencies which will be also be shown on the console as:
That’s it. Congratulations for deploying your first application on Heroku. Navigate to your URL from anywhere and you can see your website load up.
Bonus: Setting up mLabs Database Manually with Heroku
If you couldn’t install the mLab add-on to set up your MongoDB database because you do not have Credit Card details to verify your account, you can set up the database manually through mLab’s website.
To pass this step, we need to create a database from mLab and the set the MONGODB_URI manually. Create an account on mLab and verify your email.
On the homepage, click on Create new under MongoDB Deployments section to create a deployment. Next, select any Cloud Provider (preferably, Amazon Web Services) and Sandbox plan which provides 0.5GB free storage. Then, select a server region of the Cloud Provider you have chosen. Finally, enter a name for your database.
You will now see this database under MongoDB Deployments section. Now, you need to create a database user to connect to the database.
Click on the database you just created under MongoDB Deployments section. You will be redirected to the database details page.
Under the Users tab, click on Add database user. Give a database username and password in the pop-up form and click Create.
Now, the final step is to connect this database to your heroku application. To do this, copy the URI under the heading To connect using a driver via the standard MongoDB URI as shown in above figure. Here, it’s mongodb://<dbuser>:<dbpassword>@ds259111.mlab.com:59111/testdatabase (This unique MongoDB URI is different for different databases). Here, you need to replace <dbuser> the database username you just created under Users tab and <dbpassword> with its password.
Flip over to your terminal and set the copied URI as MONGODB_URI Environment variable using the command heroku config:set MONGODB_URI=<URI copied from mLab Account>
For example:
heroku config:set MONGODB_URI=mongodb://url_shortenerdb:anurag67@ds161411.mlab.com:61411/meteordb
That’s it. Now set ROOT_URL as given in previous section and push your code to Heroku by following the given instructions.
Similar process can be used to set up database of any other service provider.