Friday, September 2, 2016

Deploying the notes app with Cloud9

As a follow-up to this previous post, where we built a simple fullstack JavaScript app with MEAN, we now use Cloud9 to deploy our app in the cloud.

How to deploy MEAN with c9

First you need to setup an account. Then you get the workspace. Setup your workspace, then click Run and you're ready to go.

Create a workspace

1. Go to https://c9.io
2. Log in with your GitHub account → you will see all your repositories
3. Clone a repository (e.g. notes) to a new workspace. Choose Node.js as Workspace type.

*If cloning a repository you don't own doesn't work, then fork it and clone your fork

Setup the workspace

When you clone the repository, your workspace is created. You get a fully working Ubuntu system in the cloud. Now you can "deploy" your Notes app in the cloud. There are a few things to do before this is possible:

1. Install MongoDB by simply running the following in the command line:

sudo apt-get install -y mongodb-org

After installing, make sure to run these additional commands:

mkdir data
echo 'mongod --bind_ip=$IP --dbpath=data --nojournal --rest "$@"' > mongod
chmod a+x mongod

Then run the mongod script:

./mongod

The above is necessary due to some c9 restrictions. See this post for more information.

2. Install bower

sudo npm install -g bower

3. Now run

npm install

4. Your main server file must include the follwing:

// setup defaults if existing
process.env.PORT = process.env.PORT || 1337;
process.env.IP = process.env.IP || 'localhost';

// start server
app.listen(process.env.PORT, process.env.IP, function () {
 console.log("Server started at " + new Date())
});

If everything went well, then open a new chrome tab and type https://[app-name]-[user-name].c9users.io . For instance, deploying the notes app on my account makes it available under the following link: https://notes-roby-rodriguez.c9users.io

For a working notes workspace check out this link.

Troubleshooting

Frequently, your c9 workspace will get passivated, this meaning it's placed into a standby state after a while (since your account is free). In this case you might encounter a crash with MongoDB. On workspace activation, if the driver refuses to connect, try running the following commands:

rm data/mongod.lock
mongod --dbpath data --repair

Then run the mongod script again.