How to build the NodeJs app from scratch!

How do you build the nodejs app from scratch!

This is very very very veryyyyy basic Nodejs-ExpressJS app.
Shy of 10 lines if it gets to even that. (//todo : make even this scripted 😉 )

This app should serve “WHATEVER YOUR MESSAGE IS” whenever you hit it’s endpoint with a GET request.
We can configure where this app will be listening (I am setting it to classic 3000)

Create a new file app.js (super creative name!My creativity is dying. You make your own name. ) can write following bunch of lines in it

const express = require("express");
const app = express();

app.get("/", (req, res) => res.send(`You are Aliens!`));

app.listen(3000, () => {
  console.log(`Watching port 3000!`);
});

What this code does is it takes your GET requests on “/” point and sends out “Hello World” , you can of course replace
this message with your own dumb stuff!

Now now..
You have this little code. But as you can see we have adapted express.js library as well. You have to declare that in a .json file called package.json , let’s create that.

$ npm init
provide the inputs it asks or accept the defaults. ()
Package name : nodeapp
version (1.0.0) :
description : any you want
entry point (app.js):

Just fill in the details. In the end you will be rewarded with "package.json" file

Now head back into terminal and do

$ npm install --save express

this will add express to our dependencies at package.json file.
also we need to start this script so, get into package.json
and add

start": "node app.js",

under script module. (line 10 in code below) Save.

test with

$ npm run start

If it runs, you will see an output

“Watching port 3000!”


// This is package.json
{
"name": "simple-rest-api",
"version": "1.0.0",
"main": "app.js",
"dependencies": {
"express": "^4.16.3" //notice this. delete this comment when you copy
},
"scripts": {
"start": "node app.js"
"test": "echo \"Error: no test specified\" && exit 1"
}
}

Now that our ingredients are ready you can test this code locally, before we head into dockerization.

You must have been into some directory while all this code-shode happend. If not create one. (let’s call it nodeapp)
(again ..okay not very creative but hey no one’s dead so all good!) and put these two app.js and package.json into that,
along with yourself.

-nodeapp-YOU
|
|-app.js
|
|-package.json
|

open/navigate with your terminal here (in nodeapp directory) and

npm install
then
npm start

Now run over to your browser and open http://localhost:3000
you should see

"You are Aliens!"..

If so It worked locally. (Get me a Nobel, I caught aliens!👽 )

It’s time to dance, for reals!

Let us get Dockered.

Now that the app is ok and working, what we need to prioritize is to get stuff into container.

The best way to do that is to use something called as a "Dockerfile" (and NO I didn’t do D of docker for style, it’s meant to be.)

What’s a dockerfile you ask?
so a dockerfile in layman’s term an instruction manual for docker engine to build one image.
They are used for organizing things and greatly help with deployments by simplifying the process start-to-finish. In Dockerfile , we can define certain instructions for docker to follow while it builds your image. These instructions could be FROM what image, COPY something into container, EXPOSE certain port, RUN some command in container etc.
Since docker layers it’s design, and uses cache to build faster, the parameters that do not often change are defined first.
Our Dockerfile will look something like as below,

#Dockerfile nodejs
FROM alpine
MAINTAINER your-name-here


RUN apk add --update nodejs npm

WORKDIR /app

COPY package.json /app

RUN npm install

COPY . /app

EXPOSE 8080
CMD ["npm", "start"]

(Now you may find some slight changes in the docker file if you are reading a dated article. (So keep checking and reading.) I have added latest working config as of 15-feb-2022.)

FROM command is most important and usually the first command in a dockerfile. This command is used to specify the base image to create the container. (Images are pulled from repositories by default its dockerhub repository)

MAINTAINER command set the author of the dockerfile, it can be defined anywhere.

RUN parameter is used to execute a specific command at the build time and it’s helpful in creating the docker image.

CMD command is pretty much similar to RUN but the main difference is it’s executed “AFTER” the container has started and not during the build. This command is usually at the ends.

COPY command copies the file from to [destination] and URL are not allowed at source. It copies files from source of host to destination in container.

ADD is similar to copy but with more power as it supports the URL, When source is URL, it’s downloaded to host and then copied to container destination.

EXPOSE You can specify a port where the container application is exposed to world.

There are more but for our stuff to work this much is enough!

The important point to be noted is, I have used alpine, while there are 100s of ready node images. I used alpine because it’s lightweight and we do not need the fanfare. So it stays light.
Plus this blog is intentionally kept hands-on, so why would I rob you from the pleasures of silly mistakes and bug hunts in code?? It’s lot more fun than the code itself. (disclaimer : usually!)

The copy command seem redundant but they save time. Trust me! If not trust docker architecture which will cache the commands. Once cached these commands do not fully run, the next time around. Here npm install wouldn’t be running again. The results will be cached.
This doesn’t matter to project with 6 lines to parse.. but when it’s production, these small things save us from Gray hairs from nail biting wait of execution time. Huge time drain!!

I am done with my rant.
We need to build this image stat!
you can run following command..

Build Docker Image from Dockerfile
sudo docker build -t nodey .
Build image container
sudo docker run -it --name nodeybox -p 8080:3000 nodey

Now you should see the output
"Watching port 3000!"
as we/you defined it and since we mapped it to port 8080 just go to http://localhost:8080
should show,

"You are Aliens!"

So, Congratulations!
You are now okay with Docker basic. Have fun tweaking these to your liking.
See you when I do. Till then adios!!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s