nodejs and docker 
Tags: javascript, node, docker, serverless
Published: 2021-05-09 07:48:35

If you've ever created something that needs to 'live' somewhere other than your local machine, you know that getting an application up and running on a different machine is no easy task.There are numerous considerations to be made, ranging from the fundamentals of "how do I get my environment variables set" to which runtimes you'll require and which dependencies those will require, not to mention the need to automate the process. It is simply no longer feasible for software teams to rely on a manual deployment process.A number of technologies have attempted to address the issue of varying environments, automation, and deployment configuration, but Docker is the most well-known and perhaps most notable attempt in recent years.


A variety of innovations have attempted to solve the problem of differing environments, automation, and deployment setup, but Docker is the most well-known and perhaps most notable recent attempt.


System implementation in a Rapid scale
Cross-machine portability and reliablity
Part reuse and version control
Docker Images and Dockerfiles can be shared.
Minimal overhead with a small footprint
Maintenance is made easier.

In 2009, Node.js was first published. Big companies like Paypal, Netflix, eBay, and LinkedIn, to name a few, have used it for high-traffic web applications. It has undoubtedly been put to the test over the last ten years and has proved its worth. It also fits well with a large team, such as Spotify. At Spotify, it was used by 90 teams and 600 developers.With high scalability in mind, using Docker and Kubernetes to scale the framework horizontally becomes even simpler. High scalability is achieved by combining Docker and Node.js.


You have some experience with Node.js (express js or any other framework)
You've worked with Docker before (local development, production environments preferred)
I'm using Docker version 20.10.6, and docker-compose version 1.29.1, and I'm hoping you're using similar models.


The goal of this article is to tell you how to get a Node.js application into a Docker container. The article aims for development, and not for a production deployment.

Let's Create a simple website: Write this as the `app.js` in your editor.

```javascript
const express = require('express');

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
  res.send('Hello from Docker!');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
```

So now when you have app.js write the `package.json` file that describes your app dependencies that has all the things that was defined for the project that we have built.

```json
{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last <first.last@example.com>",
  "main": "app.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.16.1"
  }
}
```

Run npm instal with your new `package.json` file. If you're using `npm version 11 or later`, a `package-lock.json` file will be created and copied to your `Docker image`.

# Creatign the Docker File
### the most important step

In your favourite text editor, open the Dockerfile.

The first step is to determine what picture we want to build from. We'll use the most recent LTS (long-term support) 14 or any version avaialble in docke of node avaialbe during that time, which can be found on the Docker Hub:

```dockerfile
FROM node:<version avaialble in docker>
```

__but you can also use the version 14 of the node__

```dockerfile
FROM node:14
```
Then, we'll make a directory within the picture to contain the programme code; this will be the application's working directory:

```dockerfile
# Create app directory
WORKDIR /usr/src/app
```
Since this docker image already has `Node.js` and `NPM enabled`, the next step is to use the npm binary to instal the app's dependencies.

```dockerfile
# 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 ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
```

It's worth noting that we're just copying the `package.json` format, rather than the whole working directory. This enables us to use Docker layers that have been cached. Here's a good explanation from `bitJudo`. In addition, the `npm ci` order, which is mentioned in the comments, aids in providing quicker, more stable, and repeatable builds for production environments. More information on this can be found here.

**To include your app's source code in the Docker image, follow these steps.**

```dockerfile
# Bundle app source
COPY . .
```
Since your software is bound to port 8080, you'll use the EXPOSE instruction to make the docker daemon map it:

```dockerfile
#we expose the 8080 port from the localhost system
EXPOSE 8080
```

We use CMD to describe the command that will be used to run your programme. To launch your server, we'll use node server.js:

__Remember : __ We need to learn that CMD command can only be used once if even you try to use it many times the Docker will command to execute the one that is listed in the end/last of the Docker file.

```dockerfile
CMD [ "node", "server.js" ]
```

The entire docker file is given here.

```dockerfile
FROM node:14

# Create app directory
WORKDIR /usr/src/app

# 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 ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]
```

Thus you are ready to build it thus use the command

`docker run -t [name]:tag`

you will have the docker image and you can still run it with the `docker run command`.

`docker tag [source] <your username>/node-web-app`
its better that you tag it with the above format.

`docker run -p 4000:8080 -d <your repo username>/node-web-app`

When you run your picture with the `-d` option, the container is removed and runs in the background. The `-p` flag redirects a public port inside the container to a private port(that you want to run the application. Run the picture you created previously:

geting the information for the application.

```
docker logs <container id>
```

*The output:*
# Example
Running on http://localhost:8080


and now when you type `docker ps`

you will find the container running thus you can use the curl in linux and also in windows and type

`curl -i localhost:4000`

then the output is as given below.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjqxlbz97j7fsvi4wq1u.PNG)

Thank you.