Create Simple Node.js Docker Container
In this article, we’re going to create a simple Node.js hello world docker container. Let’s get started:
You can take a look at basic docker commands.Table of Contents
Create Simple Project
Let’s create a super simple Node.js project. Create a project folder named node-docker-hello-world
and go to the folder via CMD. Then run this two commands:
# init project
npm init -y
# install express.js
npm install express
Now create a file called index.js
and paste this code:
// load express module with `require` directive
var express = require('express')
var app = express()
// define request response in root URL (/)
app.get('/', function (req, res) {
res.send('Hello World!')
})
// launch listening server on port 3000
app.listen(3000, function () {
console.log('app listening on port 3000!')
})
Run the project and test it works or not:
node index.js
Our project is working. Let’s drive to next step.
Create Dockerfile
We need to define Dockerfile
to create docker container:
FROM node:alpine
WORKDIR /home/node/app
COPY package*.json index.js ./
RUN npm install
EXPOSE 3000
CMD [ "node", "index.js" ]
Create .dockerignore
and add these lines:
node_modules
.git
.cache
The .dockerignore
file works file .gitignore
.
Create Docker Image
From the root folder, run this command to build docker image:
docker build -t nodehello ./
It may take a few minutes to build image. After creating the image, we’re able to see the image using docker images
command.
Now we can run a container from the image:
docker run -d -p 3000:3000 nodehello
The app will run on port 3000. We can run the app on port 80 by this command:
docker run -d -p 80:3000 nodehello
Now visit http://localhost
and see the output. We can see the list of running containers by this command:
docker ps
The tutorial is over. You can download this project from GitHub. Thank you. ?Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.