DEV Community

kashrajiv
kashrajiv

Posted on

Creating a Docker Container for a simple Node application

Hi guys! I have always been curious about Docker. I have always wanted to play around with it and create one. Finally, I have managed to do it and as my first post, I have decided to write a small tutorial about how to create a Docker container for a very simple node application.

Docker as we all know is to create make sure that the correct dependencies have been installed for the application across multiple devices. That way, we can ensure that the app runs in that one particular way. I have therefore decided to demo this using a very simple Node application.

There are two parts to this. We will first create a Node application. And second, we create a Docker container for the node application.

Part A: Creating a Node application

Assuming that you have Node installed in your system. These are the steps that we will follow:

  1. Create an empty folder having the name of your project. In my case, its "Hello"

  2. Open up this folder in your favorite editor, and create a new file "app.js"

  3. Once you created this file, add the following code
    var msg = 'Hello World!';
    console.log(msg);

  4. Save the file, and to test the output, open a terminal and run the following command
    node app.js

The output should be "Hello World!" being printed in the console.

Part B: Creating the Docker container

Assuming that you have Docker Desktop already installed in the your system, follow the following steps

  1. From the editor, create a new file in the same directory and give the exact following name
    "Dockerfile"

  2. Open up the Dockerfile and enter the following lines
    `FROM node:14-alpine

WORKDIR /app

COPY . .

CMD ["node", "app.js"]`

Will try to explain these lines later in the post.

  1. Save the file and run the following command to build the docker image docker build -t <name> .

This line will create a new docker which you can see in the docker desktop

  1. Once this is done, run the file using the following command which will create a docker container of the image created in the previous step docker run <name>

This creates an container and runs it

You have successfully created and run a docker container for a node application.

Now to understand what the file means:
The first line specifies the base for the image, in this case, its node of version 14

The second line specifies the working directory

Third line copies all of the files from the directory

And the final line is to execute the command

Thank you!

Top comments (0)