Gitlab deploy to Heroku

Andrew Bliss
2 min readJul 24, 2018

Setting up a Gitlab deploy to Heroku is pretty easy. We will use the code from the last article to build upon our Node.js Express API.

https://medium.com/@nthchildconsulting/docker-node-js-express-server-1b55abc2e9cd

Create your Gitlab Repo

On your main Gitlab homepage click New Project

Give it the name of my-app

You will want to leave it as a private app since you will use a Heroku secret API key to deploy.

If this is your first time using Gitlab I suggest you create an SSH key to use with Git. Here is an article on how to do that.

Gitlab SSH Keys

Let’s begin by cloning the repo to our local machine.

git clone git@gitlab.com:example/my-app.git
cd my-app

You will want to change example to your own user.

Now that we have created our Gitlab repo we can now move over our code from the last article and set up some deploy scripts.

Gitlab CI

Create a file called .gitlab-ci.yml in the root of your project.

image: docker:gitservices:
- docker:dind
stages:
- build
- release
- deploy
variables:
GITLAB_GROUP: example
GITLAB_PROJECT: my-app
HEROKU_PROJECT: my-app
GITLAB_CONTAINER_TEST_IMAGE: registry.gitlab.com/$GITLAB_GROUP/$GITLAB_PROJECT:$CI_COMMIT_SHA
GITLAB_CONTAINER_RELEASE_IMAGE: registry.gitlab.com/$GITLAB_GROUP/$GITLAB_PROJECT:latest
HEROKU_CONTAINER_RELEASE_IMAGE: registry.heroku.com/$HEROKU_PROJECT/web
before_script:
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN registry.gitlab.com
build:
stage: build
script:
- docker build -t $GITLAB_CONTAINER_TEST_IMAGE .
- docker push $GITLAB_CONTAINER_TEST_IMAGE
release:
stage: release
script:
- docker pull $GITLAB_CONTAINER_TEST_IMAGE
- docker tag $GITLAB_CONTAINER_TEST_IMAGE $GITLAB_CONTAINER_RELEASE_IMAGE
- docker push $GITLAB_CONTAINER_RELEASE_IMAGE
only:
- master
deploy:
stage: deploy
script:
- docker login --username=_ --password=$HEROKU_STAGING_API_KEY registry.heroku.com
- docker build -t $HEROKU_CONTAINER_RELEASE_IMAGE .
- docker push $HEROKU_CONTAINER_RELEASE_IMAGE
- docker run --rm -e HEROKU_API_KEY=$HEROKU_STAGING_API_KEY wingrunr21/alpine-heroku-cli container:release web --app $HEROKU_PROJECT
only:
- master
when: manual

Change the GITLAB_GROUP to your own group.

This will tell Gitlab how to deploy your repo to Heroku. There are three stages. build, release, deploy

There are many predefined variables but the only one we need to care about is:

HEROKU_STAGING_API_KEY

On the left nav menu of Gitlab go to Settings > CI / CD > Variables.

Add a variable called HEROKU_STAGING_API_KEY and give it the value of your Heroku API Key. You can generate an API key by going to your Heroku settings page.

Now every time you merge into the master branch it will build a docker container ready to deploy to your Heroku account.

Go to CI / CD in Gitlab and you will be able to see your pipeline building. Then when it is ready to deploy you can click the manual play button on the right to deploy to Heroku.

--

--