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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)