在Docker容器中安裝Nodejs應用


1. 創建 Nodejs 應用

首先,編輯 package.json 文件

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last <first.last@example.com>",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.16.1"
  }
}

運行 npm install

然后創建 server.js 文件,里面定義了一個使用 Express 框架的 web 應用:

'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}`);

2. 創建 Dockerfile

新建一個 Dockerfile 文件並打開,然后輸入以下內容:

FROM node:12.13.0

# 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 [ "node", "server.js" ]

在文件夾內創建 .dockerignore 並輸入下面內容:

node_modules
npm-debug.log

3. 編譯鏡像

docker build -t node-web-app .

查看所有鏡像:

$ docker images

# Example
REPOSITORY      TAG        ID              CREATED
node            12.13.0    1934b0b038d1    5 days ago
node-web-app    latest     d64d3505b0d2    1 minute ago

4. 運行鏡像

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

5. 查看輸出

# Get container ID
$ docker ps

# Print app output
$ docker logs <container id>

# Example
Running on http://localhost:8080

6. 測試

查看端口映射:

$ docker ps

# Example
ID            IMAGE                COMMAND    ...   PORTS
ecce33b30ebf  node-web-app:latest  npm start  ...   49160->8080

使用 curl 調用 app:

$ curl -i localhost:49160

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 12
ETag: W/"c-M6tWOb/Y57lesdjQuHeB1P/qTV0"
Date: Mon, 13 Nov 2017 20:53:59 GMT
Connection: keep-alive

Hello world


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM