PM2 Deployment via Gitlab CI

Matt Chaffe
Nov 7, 2017 · 2 min read
https://unsplash.com/photos/NneNzn0vs44

If you have ever used Heroku and loved how smooth the experience is with their git based deployments. I recently set out to create a similar experience with Gitlab CI and pm2. Here is how I configured Gitlab CI to deploy a Node.js app using pm2 to my GCE instance.

Local PM2

I configured pm2 using the pm2 ecosystem command which creates a local config file, I then edited it to look like the following:

This sets out a production configuration. Which will ssh into your remote server which you should specify by changing USERNAME HOST and REPO_ADDRESS. Once connected it will update the remote git repo, npm install to ensure all dependencies are up to date and then will restart the pm2 instance.

Important

To get setup on your remote server run this command:

pm2 deploy ecosystem.config.js production setup

Gitlab

I then created my gitlab-ci.yml to look like this, I have skipped over the other stages to only show the deploy stage:

The before script is used to ensure we have ssh, bash and git so that pm2 can use them. This will also add the ssh key to the ssh-agent so that pm2 can ssh into your server.

Important

Ensure you have the private ssh_key added to your Gitlab secret variables as SSH_PRIVATE_KEY.


Thanks to Marshall Thompson

Matt Chaffe

Written by

Developer • CanJS • FeathersJS • Vue Twitter — https://twitter.com/mattchewone • Github — https://github.com/mattchewone

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade