Setting up some CI for simple Node.js project
This tutorial is my “memory card” how to set up some CI/CD features for simple node.js project. When I push changes to GitHub repository, automated tests on TravisCI are running, after successful tests TravisCI deploys the project on Heroku.
Creating project
First we create and set up our project.
-
Create repository on GitHub and initialize it with readme
-
Clone repository
git clone git@github.com:<user>/<repo>.git -
Go to the project’s folder:
cd <working_dir> -
Initialize the project:
npm init -
Install project dependencies:
npm install body-parser express mongodb mongoose --save -
Install development dependencies:
npm install expect mocha nodemon supertest --save-dev -
Add some code to create minimal working sample
-
Push to GitHub
git push
Creating Heroku application
Next, we create Heroku application. We assume that heroku CLI is installed.
-
Create Heroku application
heroku create -
Add mongolab addon to use Mongodb:
heroku addons:create mongolab:sandbox -
Push our repository to Heroku:
git push heroku master
It Works!
Integration with TravisCI
-
Create file
.travis.ymlin root directorylanguage: node_js node_js: - '6' services: - mongodb addons: apt: sources: - ubuntu-toolchain-r-test packages: - g++-4.8 -
On TravisCI add repository, enable “Build only if .travis.yml is present” and “Build pull request updates”
-
Push our project with
.travis.ymlgit push -
If we want, we can add TravisCI badge to readme.md
-
To add Slack notifications, we need to have our own Slack team. We create channel for our project, add to this channel TravisCI integration and follow the instructions.
-
It’s strongly recommended to encript the API keys. We need
travisgem to do it.gem install travis -
Add encrypted key to
.travis.yml:travis encrypt "OUR_KEY_FROM_CHANNEL_SETTINGS" --add notifications.slack -
After key is encrpted and added to
.travis.yml, we dogit pushand enjoy!
Enable Heroku notification in Slack
-
In Slack, add Heroku integration. Following the instruction, run the command in project directory:
heroku addons:create deployhooks:http --url https://hooks.slack.com/services/XXXXXXXXXXX
Enable Github notifications in Slack
- In Slack, add Github notifications. To do this, add Github integration to Slack channel, authorize to Github, select repository to integrate.
Auto-deploy to Heroku
Now we can automatically deploy our application to Heroku using TravisCI after successfull build:
-
Execute command in project directory:
travis encrypt $(heroku auth:token) --add deploy.api_key -
Add to .travis.yml lines (before encrypted Heroku token):
provider: heroku app: heroku_app_name -
Push our project to GitHub only:
git push
All work for us will be done by GitHub and TravisCI, we will receive notifications in our Slack channel.