Deploy - Node/MongoDB
Objectives
Deploy a Node/Express/MongoDB app to a production server using Heroku
Use Atlas as the mongo database
Atlas
First, let's set our app up to use Atlas instead of our local mongo database.
Create a an account here
Create a free tier cluster by following these instructions
NOTE: Step 3's screenshots haven't been updated so it may look a little different when you do it. Just make sure to choose the free tier.
TODO: Add notes about why you may pick one region over another.
Go to Securty > Network Access (from menu on left of page) to Whitelist your IP address
Whitelist your current IP address and also click the allow access from anywhere button
Go to Security > Database Access to add a user
NOTE: Make sure you know the password!!!
Click "connect", then "connect your application"
choose the NodeJS driver for step 1
copy the connection string from step 2
paste the connection string into your app:
Done! You should see something like the following when you run your Node app locally:
Protect your connection string
It's a good idea to make your connection string an environment variable, so go ahead and do that too!
Next, let's deploythe Node app to Heroku.
Deploying the app
Create a
Procfile
in the root of your Node applicationIn terminal, run
touch Procfile
. Must be called with a capitol Pmake sure it is named "Procfile" (no extention)
make sure your Procfile is in the same folder as your index.js file
in terminal type
echo "web: node index.js" >> Procfile
In your
index.js
file, where you get your server started, include the port number in your app.listen function. Example:
This ensures that when we set the PORT config variable, Heroku will run on it instead of the 3000 port (Heroku automatically includes a port that's public-facing).
Add in your Node version
Note that you may need to specify the node version you're using. To find out what version of node you're using, type the following on your terminal (from anywhere):
Then, put the following into your package.json
file:
Remove the Heroku-Postbuild script if you are launching a decoupled app and it's in your
package.json
.
Your package.json file is crucial - when you deploy your application, Heroku will check the package.json file for all dependencies so be mindful to install any dependencies you may have installed globally. You can always check your package.json to see if you are missing anything.
Before you create your app in Heroku, be sure your project is being tracked via a git repository.
Create a Heroku app via the command line
Where sitename
is the name of your app. This will create a url like: http://sitename.herokuapp.com
Commit and push all your data at this point (
git push
).To push to Heroku, enter the following command
In terminal after you deploy your app, type in
heroku ps:scale web=1
this will scale a dyno up
Go to the heroku website and add the
MONGODB_URI
to your config vars!
Last updated