Slim Coder
Posted on May 13, 2020
Table Of Contents
JavaScript
JavaScript is a multi-purpose, multi-paradigm, single-threaded programming language used on client and server-side.
Node.js
Node.js is a JavaScript runtime environment, It is responsible for running JavaScript on the server side.
You can download Node.js from here.
Node.js setup will install itself and npm (node package manager) which is use from installing dependencies.
Express.js
Express.js is the Node.js framework which is responsible for creating REST API's.
Simple Express.js Server
Now we need to create a simple Express.js:
For creating a server we need to create a new folder then inside that folder open your favorite IDE.
Now run this command (make sure you have node already installed).
npm init // This will initialize npm within directory
npm install express --save //This will install Express.js and save in package.json dependencies
mkdir index.js //Create a new file
Now add this code in index.js file:
const express = require('express'); // Require express.js framework
const app = express(); //Create a app container
app.get('/', function (req, res) { // Add a route (API)
res.send('Hello World')
});
app.listen(3000); // Listen on a port
Now your express server is ready now run this:
node index.js //This will run index.js file
Now open your browser in tab add this url http://localhost:3000.
Yahoo! Your first Express.js app is ready (Happy Hacking).
Docker
Docker is a tool designed to make it easier to create, deploy, and run applications by using containers.
This means that Docker makes our life easy by creating a container now we will create a container of our Node.js application but first download Docker from here.
Dockerized Express.js Server
Now we need to Dockerized our Node Application so add a Dockerfile in our project folder.
And add these commands inside Dockerfile.
# This file is the main docker file configurations
# Official Node JS runtime as a parent image
FROM node:9-alpine
# Set the working directory to .
WORKDIR .
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-
lock.json are copied
# where available (npm@5+)
COPY package*.json ./
# Install any needed packages
RUN npm install
# Bundle app source
COPY . ./
# Make port 3000 available to the world outside this container
EXPOSE 3000
# Run app.js when the container launches
CMD ["npm", "start"]
Now run docker build --tag node:latest and then docker run --publish 8000:8080 --detach --name bb node:latest to build and run docker image locally
Yahoo! you first dockerized application is ready to server on http://localhost:3000.
Final Note
I have created a repository all codes which we have written is inside of this repository feel free to look into the codebase.
learnwithgeeks / node-docker-session
Learn Docker with Node JS
Happy Hacking
Posted on May 13, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.