Node.js Web on Docker

Node.js Web on Docker

1. init Project

1
2
3
4
5
npm init
npm install
git init
git add .
git -commit -m "git init"

2. Edit package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"name": "nodejs_docker",
"version": "1.0.0",
"description": "nodejs_docker",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}

3. Install express.js

1
npm install express --save

4.Creat index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'use strict';

const express = require('express');

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello world\n');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

5. Creat Dockerfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FROM node:8

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "npm", "start" ]

6. Build Docker Images

1
docker build -t node-web-app .

7. Docker Run

1
docker run -p 49160:8080 -d --name node-web-app node-web-app

8. Demo

1
curl 127.0.0.1:49160

範例連結

參考