在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