DockerFile Node App

MrDevSecOps
3 min readOct 9, 2021

Node Sample application

Let’s create a simple Node.js application that we can use as our example.

Create a directory in your local machine named node and follow the steps below to create a simple REST API.

$ mkdir node 
$ cd node
$ apt install npm && npm init -y

Note: Node and npm need to install to execute the command.

$ npm install ronin-server ronin-mocks

Now, let’s add some code to handle our REST requests. We’ll use a mock server so we can focus on Dockerizing the application.

Open this working directory in your IDE and add the following code into the server.js file.

$ vi server.jsconst ronin = require('ronin-server')
const mocks = require('ronin-mocks')

const server = ronin.server()

server.use('/', mocks.server(server.Router(), false, true))
server.start()
  • The mocking server is called Ronin.js and will listen on port 8000 by default.
  • You can send GET requests to this endpoint — http://IP:8000/test and receive an array of JSON objects.
  • You can also make POST requests to the root (/) endpoint and any JSON structure you send to the server will be saved in memory.

Test the application

Let’s start our application and make sure it’s running properly. Open your terminal and navigate to the working directory you created.

$ node server.js

Get request — http://IP:8000/test

$  curl --request POST \
--url http://localhost:8000/test \
--header 'content-type: application/json' \
--data '{"msg": "testing" }'

Let’s dockerize the above application, build and run the application in Docker.

Create a DockerFile

# syntax=docker/dockerfile:1# Base Image of node 
FROM node:12.18.1
#Set ENV veriable
ENV NODE_ENV=production

#Set working Directory
WORKDIR /app
# Copy the necessy packages
COPY ["package.json", "package-lock.json*", "./"]
#Run the npm commands
RUN npm install --production
# Copy everything in current /app directory
COPY . .
# Strat the node application
CMD [ "node", "server.js" ]

Create node Docker Image with above DockerFile

$ docker build -t node-docker:v1.0.0 . 

4. Run Docker Image and Create a Container

$ docker run -d -p 80:8000 --name node-app node-docker:v1.0.0

An explanation of this command is as below,

  • -d option is used to run a container in the background and print container ID.
  • -p option is used for port mapping between container and Host machine.
  • — name option is used to assign a name to the container.
  • In the end, we provide the name of the docker image from which we wish to run our container.

Test the application.

--

--

MrDevSecOps

Integrating security into the software development lifecycle.