All tutorials
Tutorial

How to use Heroku Postgres with Koyeb Serverless Platform

6 min

Introduction

Heroku provides managed Postres databases and makes them accessible over the Internet. Whether you are an existing Heroku user wanting to deploy your apps globally while keeping your database on Heroku or looking for a place to host a managed Postgres database, this guide explains how to use and connect a Heroku Postgres database from an application running on Koyeb.

Heroku allows you to create Heroku Apps using add-ons. Since its managed PostgreSQL database is an add-on, this means you can create a Heroku app that only runs the Postgres database without having to deploy your entire application on Heroku.

In this guide, we will create a Heroku App with a Heroku Postgres add-on, create a simple Node.js application to connect the database and deploy the application on Koyeb.

Requirements

For this guide, you need:

  • A Koyeb account to deploy and run the Node application
  • A Heroku account to run the Heroku Postgress add-on
  • The Koyeb CLI installed to interact with Koyeb from the command line
  • A registry that will store our Node app Docker image that will be deployed on Koyeb

Steps

To use and connect a Heroku Postgres database on Koyeb, you need to follow these steps:

  1. Create a Heroku App with the Postgres add-on
  2. Write a Node.js app connection to the Heroku Postgres database
  3. Deploy the Node.js app on Koyeb

Create a Heroku App with the Postgres add-on

In the Heroku control panel, on the top right navigation bar, click the Create button and select Create new app. You land on the App creation form where you need to:

  • Give your application a name
  • Choose the region your App will be located: Europe or the United-States

Once the form is filled in, click the Create app button. Then click the Resources tab and in the Add-ons section of the page fill the search input with Heroku Postgres and validate. A modal opens and asks you to select the plan you want to use. In this guide, we use the Heroku Postgres add-on free tier Hobby Dev. Once the plan you want to use is selected, click Submit order form.

Write a Node.js app to connect to the Heroku Postgres database

With the Heroku Postgres add-on deployed, we will now create a basic Node application to connect the database. We will then deploy this application on Koyeb.

Initialize the environment

mkdir node-demo
cd node-demo
yarn init
yarn add express sequelize pg pg-hstore

Create the app

In the node-demo directory, create a new file app.js and paste the snippet below. The app uses Express and Sequelize to connect the Heroku database and expose an API endpoint on / to return Todo mock data from the database.

const { Sequelize } = require('sequelize')
const express = require('express')

const port = 3000(async () => {
  try {
    const sequelize = new Sequelize(process.env.PG_URL, {
      dialectOptions: {
        ssl: { sslmode: 'true', rejectUnauthorized: false },
      },
    })
    await sequelize.authenticate()
    console.log('Connection has been established successfully.')

    console.log('Create fake data.')
    const todos = sequelize.define('todos', { todo: Sequelize.TEXT })
    await sequelize.sync({ force: true })

    await todos.bulkCreate([
      { todo: 'Create a Koyeb account.' },
      { todo: 'Deploy my app.' },
      { todo: 'Enjoy!' },
    ])

    const app = express()

    app.get('/', async (_, res) => {
      items = await todos.findAll()
      res.json(items)
    })
    app.listen(port, () => {
      console.log(`Demo app listening at http://localhost:${port}`)
    })
  } catch (error) {
    console.error('Unable to connect to the database:', error)
  }
})()

Write the Dockerfile and build the Docker image

To Dockerize our Node.js app, you need to create a Dockerfile in your project folder containing the content below.

FROM node:lts as runner
WORKDIR /node-express
ENV NODE_ENV production
COPY . .
RUN npm ci --only=production
EXPOSE 3000
CMD ["node", "app.js"]

To build and properly tag the Docker image execute the following command:

docker build . -t ghcr.io/<YOUR_GITHUB_USERNAME>/node-app

In this guide, we will push the Docker image to a GitHub container registry. You are free to use another different registry as Koyeb allows you to deploy from any container registry.

Once the build is over, you can run a container using the image locally to validate everything is working as expected running:

docker run -p 3000:3000 ghcr.io/<YOUR_GITHUB_USERNAME>/node-app

As in the previous step, you can perform a curl request to ensure the app is running as expected:

$curl http://localhost:3000/
[
  {
    "id": 1,
    "todo": "Create a Koyeb account.",
    "createdAt": "2021-07-21T10:18:16.576Z",
    "updatedAt": "2021-07-21T10:18:16.576Z"
  },
  {
    "id": 2,
    "todo": "Deploy my app.",
    "createdAt": "2021-07-21T10:18:16.576Z",
    "updatedAt": "2021-07-21T10:18:16.576Z"
  },
  {
    "id": 3,
    "todo": "Enjoy!",
    "createdAt": "2021-07-21T10:18:16.576Z",
    "updatedAt": "2021-07-21T10:18:16.576Z"
  }
]

Push the Docker image to the GitHub container registry

With the Docker image built and functional, we can now upload it to the GitHub container registry. In your terminal run the command below to push the image:

ghcr.io/<YOUR_GITHUB_USERNAME>/node-app

Once the push command is completed, the Docker image is stored in your GitHub container registry.

Deploy the Node.js app on Koyeb

We are now ready to deploy our application on Koyeb. First, create a Koyeb Secret to store your container registry configuration. In this guide, we will deploy our app from the GitHub container registry. For other container registries examples, check out this related documentation.

If your Docker image is public, there is no need to create a secret containing your container registry configuration.

echo \
'{
  "auths": {
    "https://ghcr.io": {
      "username": "<REPLACE_ME_WITH_GITHUB_USERNAME>",
      "password": "<REPLACE_ME_WITH_GITHUB_TOKEN>"
    }
  }
}' | koyeb secrets create ghcr-credentials

Then, create a second secret to securely store your Heroku Postgres database connection string. You can retrieve the information from the Heroku control panel, selecting your database, clicking the Settings tab and clicking the View credentials button.

Copy the URI and create the Koyeb secret to securely store running in your terminal:

$koyeb secrets create heroku-pg-url
postgres://...

We are now ready to deploy our application, in the terminal run:

koyeb app init node-app --docker "ghcr.io/<YOUR_GITHUB_USERNAME>/node-app" --ports 3000:http --routes /:3000 --docker-private-registry-secret ghcr-credentials --env PG_URL=@heroku-pg-url

This command creates a new Koyeb App and deploys our Node application exposing port 3000 and making it publicly accessible on the / route of your Koyeb App URL.

To retrieve your Koyeb App URL and access your application, run:

$koyeb app get node-app
ID                                  	NAME           	DOMAINS                             	UPDATED AT
d58ebed1-48c0-46b7-a2f1-91f3ffdbccf2	node-app        node-app-<YOUR_ORG>.koyeb.app         2021-06-23 09:46:55.411403 +0000 UTC

Open the URL in your browser to access your application running on Koyeb. The application returns the mock Todo data stored in the Heroku Postgres database. By running your application on Koyeb you benefit from native autoscaling, automatic HTTPS (SSL), auto-healing, and global load-balancing across our edge network allowing you to make your applications faster and distribute your content near your users thanks to Koyeb's 55 edge locations.

Koyeb

Welcome to Koyeb

Koyeb is a developer-friendly serverless platform to deploy any apps globally.

  • Start for free, pay as you grow
  • Deploy your first app in no time
Start for free
The fastest way to deploy applications globally.