Prerequisites
- Node
- npm
- Docker
1. Create a node.js app
First, let’s create a simple node.js(express) application, to get started with express.
Create project by running npm init -y and copy paste the following lines in package.json file.
{
“name”: “heroku_docker”,
“version”: “1.0.0”,
“description”: “Deploy Dockerized NodeJS Image app on Heroku”,
“main”: “index.js”,
“scripts”: {
“start”: “node index.js”,
“dev”: “nodemon index.js”
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
"dotenv": "^16.0.0",
"express": "^4.18.1",
"nodemon": "^2.0.16"
}
}
Create a file named index.js which is our express app, and add the following.
const express = require("express");
require("dotenv").config();
const PORT = process.env.PORT || 3000;
const app = express();
app.use("/", (req, res, next) => {
res.send("Node JS backend is running");
});
app.listen(PORT, () => {
console.log(`Server is listing on PORT : ${PORT}`);
});
Create .env file and add PORT
PORT=3000
Now, let’s try to run our app in the terminal,
$ npm install
$ npm start
Open Browser and type localhost:3000
2. Set up the Dockerfile
The next step is to create a Dockerfile.
If you haven’t installed docker in your system, visit here to download it.
Dockerfile: you can think of the Dockerfile as a receipt — it includes instructions on how to create a Docker image
Docker image: the output of the Dockerfile run — this is the runnable unit
Add the following in Dockerfile
FROM node:alpine
# CREATE APP DIRECTORY
RUN mkdir -p /app
WORKDIR /app
# INSTALL DEPENDENCIES
COPY package*.json ./
RUN npm install
COPY . .
# Exports
EXPOSE 3000
CMD ["npm","start"]
FROM node:alpine
— From the base image node, with alpine variant.
WORKDIR
— We are mentioning that the directory calledapp
is going to hold our project. If the directory specified doesn’t exist in the image, it is newly created.
COPY package*.json ./
— We are copy our package.json and package-lock.json to our workdir.
RUN npm install
— This command installs the dependencies mentioned in our package.json.
CMD [ "npm", "start"]
— Executesnpm start
, which is the command to run our app.
3. Login to Heroku and create app
Run the following commands to login in heroku and create app on heroku. Copy the name of Heroku App.
$ heroku login
$ heroku container:login
$ heroku create
4. Build the image using Dockerfile
Being in your project directory, run the following command.
$ docker build -t registry.heroku.com/<HEROKU_APP_NAME>/web .
e.g docker build -t registry.heroku.com/heroku-docker01/web .
$ docker push registry.heroku.com/<HEROKU_APP_NAME>/web
e.g docker push registry.heroku.com/heroku-docker01/web
$ heroku container:release web -a <HEROKU_APP_NAME>
e.g heroku container:release web -a heroku-docker01
After Image release on heroku app click on open app in heroku.
Github repo — https://github.com/Abdullah0332/heroku-docker
Happy Learning!!
Top comments (0)