Deploying a Node.js Application to Heroku with Docker

D

As companies are looking to user containers and specifically Docker for deploying applications, hosting providers are working diligently to make deploying Docker applications easier. Heroku has done just that by making deploying a Docker application simple with the execution of a few command lines. I am going to walk through the steps to deploy a simple Node.js application to Heroku with docker.

Create the Node Application

If you are unfamiliar with Docker, I recommend reading up on it. I won’t be going into any great depth, as that is covered elsewhere. So to start off, I will be creating a new Node application. My package.json is below and contains a single dependency, express

{
  "name": "node-docker-heroku",
  "version": "0.0.1",
  "description": "A simple Node and Docker application deployed to Heroku",
  "main": "index.js",
  "scripts": {},
  "author": "Mark Slosarek ",
  "license": "MIT",
  "dependencies": {
    "express": "^4.16.2"
  }
}

For the application (index.js), we have a single end point that prints “Hello World”

'use strict';

const express = require('express'),
    app = express();

app.get('/', (req, res) => {
    res.send('Hello World');
});

let port = process.env.PORT || 8080;
app.listen(port, () => {
    console.log(`Application running on port: ${port}`);
});

Dockerize the Application

The Dockerfile is also very basic. It copies a few files, performs an npm install and starts the application.

FROM node:carbon

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install --only=production

COPY index.js ./

EXPOSE $PORT
CMD [ "node", "index.js" ]

Next, we will build and run the application locally to make sure it runs.

docker build -t helloworld .
docker run -d -p 8080:8080 --env PORT=8080 helloworld

Check to see if the application worked in the browser by visiting http://localhost:8080. It should display “Hello World”.

Deploying to Heroku

Deploying your docker application is quite simple.

First login to your Heroku account.

heroku container:login

Then, create the app if you don’t have one (skip this step if you have already have an application).

heroku create 

Finally, deploy your application.

You can open your application with the command below.

heroku container:push web -a 
heroku open -a 

Continue Reading

Heroku has more documentation, including how to push existing docker images, and testing your images locally.

About the author

By mark

Recent Posts

Categories