How to create a Node App within a Docker container

wchr

Wachira

Posted on May 26, 2019

How to create a Node App within a Docker container

Setup

Requirements

Before you go through this fun tutorial ensure:

  • You at least have an understanding of javascript and terminal commands.
  • You should know what Docker is and in theory how it works.
  • You have should node and npm installed on your computer. You can do this by typing this in your terminal.
$ node --version && node --version
Enter fullscreen mode Exit fullscreen mode
  • Also, since we talking containers well you need docker installed.
$ docker --version
Enter fullscreen mode Exit fullscreen mode

Create a new project

Create our project folder, where our codebase will be housed

$ mkdir docker_nodejs_app
Enter fullscreen mode Exit fullscreen mode

Let's change the directory to our app folder.

$ cd docker_nodejs_app
Enter fullscreen mode Exit fullscreen mode

Since this is a node project, we need a package.json file to track our project dependencies.

To create one pretty fast type this in your terminal.

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

We will be using express as our default node web framework.

$ npm install express --save # Introduce the save flag to track it in the package.json file
Enter fullscreen mode Exit fullscreen mode
{
  "name": "docker_node_app",
  "version": "1.0.0",
  "description": "nodejs image demo",
  "author": "your name",
  "license": "MIT",
  "main": "app.js",
  "keywords": [],
  "scripts": {
      "start":"node app.js"
  },
  "dependencies": {
    "express": "^4.16.4"
  }
}
Enter fullscreen mode Exit fullscreen mode

Create and run our server

We will create a simple express server. Let's create the file that will hold our server code.

You can use the terminal to create the file

$ touch app.js # Creates the file from the terminal
Enter fullscreen mode Exit fullscreen mode

Or your locally installed code editor.

Let us write our server code.

"use strict"; // Ensures our code is compiled in strict mode

// Lets import our web framework
var express = require("express");

// Initialise our app
const app = express();

// Lets set our port
/**
 * The default port number is `3000`
 * Take note on that as we will come to that.
 */
app.set("port", 3000);

/**
 * To ensure works as it should we will create a
 * simple endpoint to return a json response
 */

// Define our json response
const data = {
  blog_name: "docker_nodejs_app",
  blog_author: "wachira (tesh254)",
  blog_author_twitter: "@wachira_dev"
};

// Define out GET request endpoint
app.get("/", (req, res) => {
  res.status(200).json(data);
});

// Initialize our server
app.listen(app.get("port"), () => {
  console.log(`Server listening on port ${app.get("port")}`);
});

Enter fullscreen mode Exit fullscreen mode

Let's run it, it's a simple server meaning its bug-free.

$ node app.js
Enter fullscreen mode Exit fullscreen mode

You should see the same text on your terminal.

Screenshot 2019-05-22 at 4.07.38 PM.png

Let's test our endpoint on our browser.

Screenshot 2019-05-22 at 5.27.21 PM.png

Finally what the blog is about.....DOCKER

For you to run your server within a container you a couple of things:

  • Dockerfile: defines what goes on in the environment inside your container.
  • docker-compose.yml: Not a must but comes in handy if you plan to add services like a database
  • Dependency file: Contains the packages needed to run your application successfully e.g. package.json file for node or requirements.txt for python.
  • .dockerignore: Not a must but it allows you to exclude files from the context like a .gitignore file allows you to exclude files from your git repository.

Let's create and write our Dockerfile

$ touch Dockerfile
Enter fullscreen mode Exit fullscreen mode

You can copy and paste the configurations to your Dockerfile.

# Define the image we will use and version
# latest just means we need the latest nodejs image available
FROM node:8

# Create an app directory to hold the application code
WORKDIR /usr/docker_nodejs_app/src/app

# Duplicate the dependency file to the container's project root directory.
COPY package*.json ./

# Install app dependencies
RUN npm install

# Bundle app source inside the docker image
COPY . .

# Expose our app port inside the app and 
EXPOSE 3000:3000

# Define commands that will run the app
CMD ["npm", "start"]

Enter fullscreen mode Exit fullscreen mode

Turn to your terminal and build your container.

$ docker build -t docker_nodejs_app .
Enter fullscreen mode Exit fullscreen mode

You should see something like this on your terminal when your build is done.

Screenshot 2019-05-22 at 5.30.55 PM.png

Let's run our app from docker

$ docker run -it docker_nodejs_app
Enter fullscreen mode Exit fullscreen mode

If you did everything in this tutorial right then you should see something similar to the screenshot below.

Screenshot 2019-05-22 at 5.42.09 PM.png

Test it out on a browser, the same results expected.

This tutorial will be a series, this being the first part. The parts will be as follow:

  • Introducing services to our app, spoiler alert, MongoDB.
  • Hosting our docker container on Heroku.
  • Push our repo to the Docker repository.
  • Other commands with Docker that make your experience worthwhile.

Extras

💖 💪 🙅 🚩
wchr
Wachira

Posted on May 26, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related