Dockerizing Your Node.js Application
Tags: docker, node, beginners, tutorial
Published: 2022-05-18 05:54:15

Learn all about Dockerizing your Node application in this short but sweet step-by-step tutorial with code blocks. Try it today!

Docker has completely revolutionized the way we build, package, and ship software. Docker has made it possible for developers to package their applications and share them with others. It is because of Docker that we now see so many advancements in cloud computing. Many emerging startups keep Docker technology as their base. Additionally, Docker enhanced the DevOps approach by bridging the gap between Dev and Ops teams. Today, we will walk through a simple tutorial demonstrating how you can build a simple ‘Hello World’ application—and we’ll be Dockerizing it. 

### Pre-requisites:
- Download and install Docker from the [official website](https://docs.docker.com/get-docker/).
- Install Node.js from the official website [here](https://nodejs.org/en/).
- Install npm from the official website [here](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).

### Tutorial
#### Create An Application
Create a directory to store your application and dependencies. You can choose any name you want. I am choosing the name ‘expapp’.

`mkdir expapp`

Initialize the application with the command `npm init -y`. This will create your _package.json_ file with your dependencies, along with the name and description of the application.

```
{
 "name": "expapp",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "test": "mocha"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
}
```

We will add the Express framework as a dependency by running the following command on the project’s root directory.

`npm install express --save`

Once you add this dependency, you can go back and check your _package.json_ file. It should now have the express dependency listed.

```
{
 "name": "expapp",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "test": "mocha"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "dependencies": {
   "express": "^4.17.3"
 }
}
```

Once you add express as a dependency, you should see two more files created in your main directory: _package-lock.json_ and node_modules. We will not go into detail as this is not the objective of this tutorial. If you really want to know more, you can go through this getting started guide.

Now, it is time to add our main code to the _app.js_ file. 

Create a file named _app.js_ and add the following code:

```
const express = require('express');
 
const app = express();
const PORT = process.env.PORT || 3002;
 
app.get('/', (request, response) => {
 response.status(200).json({
   message: 'Hello Docker!',
 });
});
 
app.listen(PORT, () => {
 console.log(`Server is up on localhost:${PORT}`);
});
```

In the above file, we are configuring the app—basically making express a required dependency, and making the app start a server and listen on port 3002 for connections. The app responds with **{“message”: “Hello Docker!”}** for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

Our simple application is ready. Now, we can test to see if it works properly by running it. Run the command `node app.js` and you should see the output below when you hit the http://localhost:3002/.


![localhost](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kmr7ma2z6mg6nz2s33gv.png)

### Create a Dockerfile
Let’s create a Dockerfile to make an image of our application. Go to the root directory of your application, create a file named ‘_Dockerfile_,’ and add the following code to it.

```
FROM node:14-alpine AS development
ENV NODE_ENV development
# Add a work directory
WORKDIR /app
# Cache and Install dependencies
COPY package.json .
RUN npm install
# Copy app files
COPY . .
# Expose port
EXPOSE 3002
# Start the app
CMD [ "node", "app.js" ]
```

Here in the Dockerfile, we are using Node:14-alpine as the template for our image.

Set the working directory in the container to /app. We will use this directory to store files, run npm, and launch our application, exposing the port 3002 for our application to run.

Finally, the last line specifies how our application will start.

**Optional:**
Create a .dockerignore file to prevent your local modules and logs to be copied onto your Docker image. Mention these two things: _node_modules_ and _npm-debug.log_ in your .dockerignore file.

### Build an Image of the Application
Once you save the file in your root directory, let’s build an image with the Dockerfile we just wrote. This can be done with the following Docker build command.

`docker build -t express-app .`
-t parameter sets a name for your Docker image.
I am naming my image exp-app. You can name yours whatever you want :)
Once the command runs successfully, you should verify the image built by using the command `docker images`

![build with dockerfile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0fx3ep8khtyo6a29h81.png)

#### Launch the Container
The image is built!ad It’s time to launch the Docker container with assigned ports using the following command: 
`docker run -p 3002:3002 express-app`

#### Push to Docker Hub
Now, let’s push this image to our Docker hub. Make sure you are logged into your Docker hub from your terminal. You can do this by using the command `docker login`.

You need to build the image again using your Docker hub credentials.
`docker build -t [USERNAME]/express-app .`
Add your username in the specified field above – it is your Docker hub username.

Once you build it with your Docker hub credentials, push it to your Docker hub using the command `docker push [USERNAME]/express-app.`

You should see a new image pushed to your Docker hub. You can verify this by going to your Docker hub dashboard:

![Docker Hub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8tg7rjl9l9pkkl0z7tk4.png)

Great! Now, you can use this image anywhere. Share it with your fellow developers and reduce the time and effort to rebuild it on their machines.

Verify if we have pushed the right image to Docker Hub by running the below command:
`docker run [USERNAME]/express-app`

You should see the application running on the specified port with the following output:

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vgbn5gspk3uwcahykbla.png)

Check that by going to your http://localhost:3002/.

![Hello Docker](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pa1ihcrp88m8vr1qajr8.png)

You’re One Step Closer to Being a Docker Pro Congratulations! You created an application, built an image of the application, and pushed it to the Docker Hub container registry Hub. 

Not a fan of copying and pasting code blocks from blog posts? You can see all the code in this application’s [GitHub repository](https://github.com/pavanbelagatti/Simple-Node-App).

You got an idea on how to build a simple application and Dockerize it, the next step is to deploy this application to the cloud. We will consider Kubernetes as our platform to deploy this app for all the good reasons and in our next tutorial, we’ll go over how to deploy a Node.js application to Kubernetes. Well, you can easily automate the continuous delivery and deployment using the [Harness platform](https://app.harness.io/auth/#/signup/?utm_source=reddit&utm_medium=social&utm_campaign=community&utm_content=pavans_dockerizing_article&utm_term=get-started). 

![Harness CD](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylimhix5e3znekenxa5g.png)

I'll also show you how to do that in this series of tutorials.