使用portainer管理docker化node应用

现在假设你知道并且已经装好docker和node,知道基本概念,那么接下来的操作有两部分

  • portainer管理容器
  • docker化node应用

效果如下图



portainer管理容器

1
2
3
docker pull portainer/portainer
docker volume create portainer_data
docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

打开 http://localhost:9000,选择local,设置用户名和密码进入即可。

docker化node应用

1、建一个node app例如名为docker_web_app,将必要的文件创建完毕

1
2
3
mkdir docker_web_app
cd docker_web_app
touch package.json index.js .dockerignore Dockerfile

2、将下面json贴入package.json并执行npm i,安装express

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"name": "docker_web_app",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "xxxx@xxx.xxx",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.16.1"
}
}

3、将下面代码贴入index.js,这里是主要的运行代码

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

const express = require('express');

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

const app = express();
let temp = 0;
app.get('/', (req, res) => {
console.log(++temp);
res.send('Hello world\n');
});

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

4、让docker镜像忽略一些文件,在.dockerignore中加入下面内容

1
2
node_modules
npm-debug.log

5、编写Dockerfile用于构建镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FROM node:8

# 应用所在目录
WORKDIR /usr/src/app

# 安装依赖
COPY package*.json ./
RUN npm install

# 复制源码
COPY . .

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

6、让node容器跑起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 在docker_web_app目录下build镜像,可能需要去docker官网注册账号
docker build -t <your username>/node-web-app .

# 查看刚刚build的镜像
docker images

# 运行容器
docker run -p 10000:8080 -d <your username>/node-web-app

# 查看刚刚生成的容器
docker ps

# 查看日志
docker logs <container id>

# 进入容器中
docker exec -it <container id> /bin/bash

测试是否成功
curl -i localhost:10000

返回类似下列内容说明成功
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: Sat, 11 Aug 2018 09:45:00 GMT
Connection: keep-alive

Hello world

现在打开 http://localhost:9000,进入到开始图中即可看到容器内的运行情况。
配合gitlab-ci,编写好gitlab.yml文件,即可实现自动构建镜像部署应用,即简单的DevOps。

◀        
        ▶