Here’s a step-by-step guide to creating a simple “Hello World” Node.js application and dockerizing it.
Step 1: Set Up the Node.js Application
1. Install Node.js and npm: Ensure that Node.js and npm are installed on your system. You can download them from here. Try the below commands in your system
2. Create a Project Directory: Create a project directory node-app and navigate to that folder..
3. Initialize a New Node.js Project: To initialize a node project, run the command npm init -y in the same working directory you created in the previous step. Once you initialize you can see that package.json file with default values.
4. Create the Application File: Create an index.js file in your project directory and add the following code:
5. Update package.json Scripts: Open the package.json file and update the scripts section to include a start script and after adding, it should look as below.
6 . Test the Application: Now you can run ‘npm start’ command in your project directory and Open your browser and go to http://localhost:3000 or http://0.0.0.0:3000 to see “Hello Nodejs World!”. Note, we defined port number 3000 in index.js to listen. Also you can verify that application is listening in this port via netstat utlity.
Step 2: Dockerize the Application
1. Create a Dockerfile: In the your project directory,ie the directory named ‘node-app’ where you placed index.js and package.json file ,create a file named Dockerfile and add the following content:
FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ “npm”, “start” ]
EXPOSE 3000
Also, you can copy the content from this link
2. Create a .
dockerignore File: Create a .dockerignore file to exclude files and directories from the Docker build context that are not needed in the container, add the following content to .dockerignore file
node_modules
npm-debug.log
Please see below screenshots for Dockerfile and .dockerignore file
3. Build the Docker Image: Run the command ‘docker build -t nodeapp . ‘ to build your Docker image:
4. Check the image availability on your local machine after the build by running the command as in the screenshot below
5 . Run the Docker Container: Once the image is built, run a container from the image:
And now open your browser and go to http://localhost:3000 or http://0.0.0.0:3000 to see “Hello Nodejs World!”.
Also, you can open another tab in the terminal and see the running container by running the command as in the screenshot below
Conclusion
You have now created a simple Node.js “Hello Nodejs World” application and dockerized it. You can refer to my public repo here for reference