/

Building a Simple Node.js Hello World Docker Container from Scratch

Building a Simple Node.js Hello World Docker Container from Scratch

In this blog post, we will walk through the process of creating a simple Node.js Hello World Docker container. We will start with a basic Node.js Dockerfile and then build an image from it.

First, let’s take a look at the Dockerfile:

1
2
3
4
5
6
FROM node:14
WORKDIR /usr/src/app
COPY package\*.json app.js ./
RUN npm install
EXPOSE 3000
CMD ["node", "app.js"]

Note: Make sure to use double quotes in the CMD line. Using single quotes will result in an error.

To begin, create a new folder called “examplenode” inside the “dev/docker” directory. In this folder, create a file called “app.js” and add the following code:

1
2
3
4
5
const express = require('express')
const app = express()

app.get('/', (req, res) => res.send('Hello World!'))
app.listen(3000, () => console.log('Server ready'))

This is a simple Node.js application using Express. Before we proceed, we need to add the Express dependency to the package.json file. Run the following command to initialize the package.json file and install Express:

1
2
npm init -y
npm install express

Once the installation is complete, you can run node app.js to verify that the application works as expected.

Now let’s create the Docker image. In the same folder as the “app.js”, “package.json”, and “package-lock.json” files, create a file called “Dockerfile” (without any file extension). You can safely delete the “node_modules” folder at this point since we will include it in the .dockerignore file to exclude it from the Docker image build process. The .dockerignore file works similarly to the .gitignore file in Git.

To build the Docker image, run the following command:

1
docker build -t examplenode .

This command will download the Node image, run npm install, and build the Docker image. Note that after the initial download of the base image (e.g., “node”), subsequent builds will be faster as the image will be cached locally.

Once the image is built, we can create a container from it using the following command:

1
docker run -d -p 3000:3000 --name node-app examplenode

Now you can see the container running in Docker Desktop. To access the application, you can click the “Open in browser” button next to the container in Docker Desktop. The application will be running on port 3000.

If you want to run the application on a different port, you can modify the port mapping when running the container. For example, to run the application on port 80, use the following command:

1
docker run -d -p 80:3000 --name node-app examplenode

That’s it! You have successfully built a Docker container for a simple Node.js Hello World application. With Docker, you can easily isolate and run your applications in containers, providing flexibility and portability.

Tags: Docker, Node.js, Containerization, Express