Setting up GitLab CI with dokku

Thanks to these posts by Andy Smith and Nelson Romero I was able to set up my GitLab repos to deploy to my dokku instance whenever master is updated (so a git push or when a merge request is accepted and merged).

NOTE: Subsitute dokku.me with your own domain.

Create ssh key for deployment:

ssh-keygen -P '' -C 'GitLab/Dokku Integration' -f gitlab

Copy gitlab.pub to your dokku instance:

scp gitlab.pub me@dokku.me:/home/me/

ssh to your dokku and add the public key above:

sudo dokku ssh-keys:add "GitLab/Dokku Integration" $(pwd)/gitlab.pub

Then go to the Settings -> CI/CD -> Variables for your GitLab repo and configure some environment variables:

SSH:

Set the APP_NAME to the name of your existing dokku app:

Back to your local copy of your repo, create some scripts to be called by the GitLab runner:

mkdir scripts
touch scripts/{pre-deploy,deploy}
#!/usr/bin/env bash

git checkout master
git pull
git push dokku@dokku.me:$APP_NAME master
scripts/deploy
#!/usr/bin/env bash

mkdir -p ~/.ssh
echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H 'dokku.me' >> ~/.ssh/known_hosts
scripts/pre-deploy

Make the scripts executable:

chmod +x scripts/*

Then create .gitlab-ci.yml, which will configure the GitLab CI:

default:
  before_script: 
    - ./scripts/pre-deploy

stages:
  - deploy

deploy_to_dokku:
  stage: deploy
  script: ./scripts/deploy
  only:
    - master

Commit these files to your repo and push to GitLab (assuming origin is GitLab):

git add scripts .gitlab-ci.yml
git commit -am "Set up GitLab-CI"
git push origin master

This should trigger the pipeline to run. You can check the status by going to your GitLab repo -> CI/CD -> Jobs.