Use Gitlab-CI to deploy Docker images to Heroku

Niel de Wet
2 min readOct 4, 2018

--

Gitlab-CI offers a powerful way to automate building and releasing software, and Docker offers a standardized way to ship software. Heroku, in turn, is a convenient place to deploy web applications. All off these services can also be used for free, within certain limitations.

In this post I will describe how to compose these services into automated Continuous Integration and Continuous Deployment. I assume that you already have a working Docker build.

Step 1: Prepare your application to run on Heroku

Configure your application to listen for connections on the port defined by the environment variable $PORT. This variable is set by the Heroku runtime and incoming requests are forwarded to your application on this port.

Heroku runs docker apps a a non-root user. Add and use a user in your Dockerfile, before the CMD statement:

RUN adduser -D myuser
USER myuser

Step 2: Perform the initial deployment of your application using the Heroku CLI

Log in to the Heroku Container Registry:

heroku container:login

Build and push the container, tagged as “web”:

heroku container:push --app my-awesome-app --context-path . web

Release the image you just pushed with the “web” process type:

heroku container:release --app my-awesome-app web

Step 3: Configure your Gitlab pipeline

Start by adding your Heroku authorization token to pipeline settings. Go to Settings > CI / CD > Variables. Retrieve your token by running heroku auth:token and save it as a Gitlab CI/CD variable named “HEROKU_TOKEN”.

Now adapt this .gitlab-ci.yml file according to your needs:

Line 14: Build the image based on your own Dockerfile and save the image ID in a file named “imageid.txt”.
Line 15: Log in to the Heroku Docker registry.
Line 16: Push the image.
Line 17: Install cURL.
Line 19: Start a YAML block scalar, ignoring the trailing newline.
Line 20: Use cURL to HTTP PATCH the “web” process type of the formation resource of your Heroku app with the new Docker image ID.

With this in place, commit your changes and watch the image automatically deployed to your Heroku app!

--

--

Responses (2)