得益于 node 的横空出世以及前端工程化的兴起,不管是开发模式,仍是开发框架,前端生态链都产生了翻天覆地的变化,与此同时前端慢慢开始向其余领域探索,项目部署就是其中一个领域javascript
在刀耕火种的时代,当执行 npm run build
将生成产物交给运维后,前端的任务就算完成了,运维同窗在生产服务器上将产物的路径写入 nginx 配置文件,至此完成了“简单”的部署html
随着项目的不断迭代,前端开始发现问题的严重性,每次都须要耗费大量的时间在打包上,开发5分钟,打包半小时的状况家常便饭
,另外开发者自身环境的差别会致使最终的产物也有不一样前端
但办法总比困难多,例如能够将打包操做放到远端服务器上,又好比能够将上述流程结合 git 仓库实现自动部署vue
本着不设边界的“字节范”,本文将从零开始,实现前端自动化部署流程,打开项目部署的“黑盒”java
涉及技术栈以下:node
文章中的命令大部分为 linux 命令,本地是 windows 系统的读者请使用 git bash
mysql
着手开发前,先介绍此次的主角 docker
linux
简而言之,docker 能够灵活的建立/销毁/管理多个“服务器”,这些“服务器”被称为 容器 (container)
nginx
在容器中你能够作任何服务器能够作的事,例如在有 node 环境的容器中运行 npm run build
打包项目,在有 nginx 环境的容器中部署项目,在有 mysql 环境的容器中作数据存储等等git
一旦服务器安装了 docker ,就能够自由建立任意多的容器,上图中 docker 的 logo 形象的展现了它们之间的关系,🐳就是 docker,上面的一个个集装箱就是容器
为了方便本地调试,能够先在本地安装 docker
Mac:download.docker.com/mac/stable/…
Windows:download.docker.com/win/stable/…
Linux:get.docker.com/
下载安装完毕后,点击 docker 图标启动 docker,此时在终端中就可使用 docker 相关的操做
出现如下状况,检查 docker 应用程序是否正常启动
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
复制代码
docker 有三个重要的概念
若是把容器比做轻量的服务器,那么镜像就是建立它的模版,一个 docker 镜像能够建立多个容器,它们的关系比如 JavaScript 中类和实例的关系
有两种方式获取镜像
Dockerfile 是一个配置文件,相似 .gitlab-ci.yml/package.json,定义了如何生成镜像
尝试用 Dockerfile 建立 docker 镜像
首先建立一个 hello-docker
目录,在目录中建立 index.html
和 Dockerfile
文件
<!--index.html-->
<h1>Hello docker</h1>
复制代码
# Dockerfile
FROM nginx
COPY index.html /usr/share/nginx/html/index.html EXPOSE 80
复制代码
/usr/share/nginx/html
是容器中 nginx 默认存放网页文件的目录,访问容器 80 端口会展现该目录下 index.html 文件其余 Dockerfile 配置参考官方文档
此时,你的文件结构应该是
hello-docker
|____index.html
|____Dockerfile
复制代码
在建立 Dockerfile 文件后,在当前目录运行如下命令能够建立一个 docker 镜像
docker build . -t test-image:latest
复制代码
test-image
的镜像,并标记为 latest(最新)版本经过 docker images
命令查看全部镜像
镜像成功建立后,运行如下命令能够建立一个 docker 容器
docker run -d -p 80:80 --name test-container test-image:latest
复制代码
test-image
最新版本的镜像建立容器经过 docker ps -a
命令查看全部容器
因为本地 80 端口映射到了容器的 80 端口,因此当输入 localhost
时,会显示 index.html 文件内容
若是说 github 是存储代码的仓库,那么 dockerhub 就是存储镜像的仓库
开发者能够将 Dockerfile 生成的镜像上传到 dockerhub 来存储自定义镜像,也能够直接使用官方提供的镜像
docker pull nginx
docker run -d -p 81:80 --name nginx-container nginx
复制代码
第一步拉取了官方的 nginx 镜像,第二步用基于官方 nginx 镜像建立名为 nginx-container
的容器
因为上一步操做本地 80 端口已经被占用了,这里使用 81 端口映射到容器的 80 端口,访问 localhost:81
能够看到 nginx 启动页面
了解了 docker 的概念和使用方法,接着讲讲为何要用 docker
有人会问,环境我均可以装在本身的服务器上,为何还要放在一个个容器里呢?这里列举使用 docker 的几个优势
docker 的出现解决了一个世纪难题:在我电脑上明明是好的
:)
开发者能够将开发环境用 docker 镜像上传到 docker 仓库,在生产环境拉取并运行相同的镜像,保持环境一致
docker push yeyan1996/docker-test-image:latest
本地提交名为 docker-test-image
的镜像,镜像名须要加上 dockerhub 帐号做为前缀
docker pull yeyan1996/docker-test-image:latest
服务器拉取帐号 yeyan1996
下的 docker-test-image
镜像
相似 git,docker 也有版本控制
在建立镜像时可使用 tag 标记版本,若是某个版本的环境有问题,能够快速回滚到以前版本
使用 docker 可使你的服务器更干净,构建用到的环境能够都放在容器中
相比于真实服务器/虚拟机,容器不包含操做系统,这意味着建立/销毁容器都十分高效
介绍完 docker,接着咱们从零开始实现前端自动化部署
在没迁移 Docker 以前,若我想更新线上网站中内容时,须要:
npm run build
生成构建产物git push
提交代码到仓库在实现前端自动化部署后:
git push
提交代码到仓库npm run build
生成构建产物能够发现,实现前端自动化部署后开发者须要作的只是把代码推到仓库,其他的事均可以经过服务器上的自动化脚本完成
首先你得有一台服务器吧-。-
因为是我的项目,对云服务器的要求不高,大部分供应商会给新用户白嫖免费试用 1-2 周,这里我选择腾讯云 CentOS 7.6 64位
的操做系统,固然阿里云或其余云服务器也彻底 ok
熟悉云服务器配置或者不是腾讯云的读者能够跳过这章
注册相关的操做不细说了,参考供应商教程,随后登录控制台能够看到当前云服务器的公网 IP,例以下图中服务器的公网 IP 是:118.89.244.45
公网 IP 用于以后 webhook 发送请求的地址
而后咱们须要登录云服务器,本地登录云服务器的方式通常有两种,密码登录和 ssh 登录(或者用 ssh 工具,windows 系统能够用 xhell,macOS 能够用 putty)
前者无需配置,但每次登录都须要输入帐号密码,后者须要注册 ssh 密钥,但以后能够免密登录云服务器。我的比较喜欢后者,因此先在控制台注册 ssh 密钥
生成密钥的方式同 git,以前生成过的话本地执行如下命令就能查看
less ~/.ssh/id_rsa.pub
复制代码
没有生成过密钥本地运行如下命令便可,参考 服务器上的 Git - 生成 SSH 公钥
$ ssh-keygen -o
Generating public/private rsa key pair.
Enter file in which to save the key (/home/schacon/.ssh/id_rsa):
Created directory '/home/schacon/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/schacon/.ssh/id_rsa.
Your public key has been saved in /home/schacon/.ssh/id_rsa.pub.
The key fingerprint is:
d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 schacon@mylaptop.local
复制代码
$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaCxxxxxxxxxxxxxxxxxxxxxxxxBWDSU
GPl+nafzlHDTYxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxPppSwg0cda3
Pbv7kOdJ/MxxxxxxxxxxxxxxxxxxxxxxxxxxxQwdsdMFvSlVK/7XA
t3FaoJoxxxxxxxxxxxxxxxxxxxxx88XypNDvjYNby6vw/Pb0rwert/En
mZ+AW4OZPnTxxxxxxxxxxxxxxxxxxo1d01QraTlMqVSsbx
NrRFi9wrf+M7Q== schacon@mylaptop.local
复制代码
将生成的公钥放在云服务器控制台图示部分,点击肯定
除了注册公钥,还须要将它绑定实例,将实例关机并进行绑定
绑定完成后从新开机,至此就能够在本地经过 ssh 命令登录云服务器啦
ssh <username>@<hostname or IP address>
复制代码
接着给云服务器安装基础的环境
以前在本地安装了 docker,但云服务器上默认也是没有的,因此须要给它也安装 docker 环境
云服务器安装和本地有些区别,根据 docker 官网 的安装教程,运行如下命令
# Step 1: 安装必要的一些系统工具
sudo yum install -y yum-utils
# Step 2: 添加软件源信息,使用阿里云镜像
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3: 安装 docker-ce
sudo yum install docker-ce docker-ce-cli containerd.io
# Step 4: 开启 docker服务
sudo systemctl start docker
# Step 5: 运行 hello-world 项目
sudo docker run hello-world
复制代码
弹出 Hello from Docker!
证实 Docker 已经成功安装啦~
自动化部署涉及到拉取最新的代码,因此须要安装 git 环境
yum install git
复制代码
因为 SSH 方式还须要在 github 上注册公钥,方便起见,以后会选择 HTTPS 的方式克隆仓库
既然是前端自动化部署,云服务器上相关处理逻辑用 js 编写,因此须要安装 node 环境,这里用 nvm 来管理 node 版本
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
复制代码
接着须要将 nvm 做为环境变量
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
复制代码
经过 nvm 安装最新版 node
nvm install node
复制代码
node 安装完成后,还须要安装 pm2
,它能使你的 js 脚本能在云服务器的后台运行
npm i pm2 -g
复制代码
简单使用 vue-cli 在本地建立项目
vue create docker-test
复制代码
并将 demo 项目上传到 github,准备配置 webhook
hook 翻译为“钩子”,还能够理解为“回调”
参考 Vue 生命周期,当组件挂载完成时会触发 mounted 钩子,在钩子中能够编写拉取后端数据,或者渲染页面等回调逻辑,而 github 的 webhook 会在当前仓库触发某些事件时,发送一个 post 形式的 http 请求
当仓库有提交代码时,经过将 webhook 请求地址指向云服务器 IP 地址,云服务器就能知道项目有更新,以后运行相关代码实现自动化部署
打开 github 的仓库主页,点击右侧 settings
Payload URL:填写云服务器公网 IP,记得添加 http(s) 前缀
Content type:选择 application/json 即发送 json 格式的 post 请求
触发时机:Just the push event,即仓库 push 事件,根据不一样的需求还能够选择其余事件,例如 PR,提交 Commit,提交 issues 等
webhook 还能够设置一些鉴权相关的 token,因为是我的项目这里不详细展开了
点击 Add webhook
为当前项目添加一个 webhook,至此,当 docker-test
项目有代码提交时,就会往 http://118.89.244.45:3000
发送一个 post 请求
配置完成后,能够向仓库提交一个 commit,而后点击最下方能够看到 post 请求参数
参数主要涉及当前仓库和本地提交的信息,这里咱们只用 repository.name
获取更新的仓库名便可
当云服务器接收到项目更新后发送的 post 请求后,须要建立/更新镜像来实现自动化部署
先在本地项目里新建一个 Dockerfile 用于以后建立镜像
# dockerfile
# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html EXPOSE 80
CMD ["nginx", "-g", "daemon off;"] 复制代码
逐行解析配置:
lts-alpine
版本镜像,并经过构建阶段命名,将有 node 环境的阶段命名为 build-stage
(包含 alpine 的镜像版本相比于 latest 版本更加小巧,更适合做为 docker 镜像使用)npm install
在容器中安装依赖npm run build
在容器中构建这里用到了 docker 一个技巧:多阶段构建
将构建分为两个阶段,第一阶段基于 node 镜像,第二阶段基于 nginx 镜像
stable-alpine
版本镜像,并将有 nginx 环境的阶段命名为 production-stage
build-stage
阶段生成的产物,将其复制到 /usr/share/nginx/htmlnginx -g daemon off
命令,一旦 CMD 对应的命令结束,容器就会被销毁
,因此经过 daemon off 让 nginx 一直在前台运行最后经过 scp
命令,将 Dockerfile 文件复制到云服务器上
scp ./Dockerfile root@118.89.244.45:/root
复制代码
相似 .gitignore,.dockerignore 能够在建立镜像复制文件时忽略复制某些文件
本地项目里新建 .dockerignore
# .dockerignore
node_modules
复制代码
因为须要保持本地和容器中 node_module 依赖包一致,在建立 Dockerfile 时用了两次 COPY
命令
第一次只复制 package.json 和 package-lock.json,并安装依赖
第二次复制除 node_modules的全部文件
接着将 .dockerignore 文件也复制到云服务器上
scp ./.dockerignore root@118.89.244.45:/root
复制代码
因为咱们是前端开发,这里使用 node 开启一个简单的 http 服务器处理 webhook 发送的 post 请求
本地项目里新建 index.js
const http = require("http")
http.createServer((req, res) => {
console.log('receive request')
console.log(req.url)
if (req.method === 'POST' && req.url === '/') {
//...
}
res.end('ok')
}).listen(3000,()=>{
console.log('server is ready')
})
复制代码
当项目更新后,云服务器须要先拉取仓库最新代码
const http = require("http")
+ const {execSync} = require("child_process")
+ const path = require("path")
+ const fs = require("fs")
+ // 递归删除目录
+ function deleteFolderRecursive(path) {
+ if( fs.existsSync(path) ) {
+ fs.readdirSync(path).forEach(function(file) {
+ const curPath = path + "/" + file;
+ if(fs.statSync(curPath).isDirectory()) { // recurse
+ deleteFolderRecursive(curPath);
+ } else { // delete file
+ fs.unlinkSync(curPath);
+ }
+ });
+ fs.rmdirSync(path);
+ }
+ }
+ const resolvePost = req =>
+ new Promise(resolve => {
+ let chunk = "";
+ req.on("data", data => {
+ chunk += data;
+ });
+ req.on("end", () => {
+ resolve(JSON.parse(chunk));
+ });
+ });
http.createServer(async (req, res) => {
console.log('receive request')
console.log(req.url)
if (req.method === 'POST' && req.url === '/') {
+ const data = await resolvePost(req);
+ const projectDir = path.resolve(`./${data.repository.name}`)
+ deleteFolderRecursive(projectDir)
+ // 拉取仓库最新代码
+ execSync(`git clone https://github.com/yeyan1996/${data.repository.name}.git ${projectDir}`,{
+ stdio:'inherit',
+ })
}
res.end('ok')
}).listen(3000, () => {
console.log('server is ready')
})
复制代码
data.repository.name
即 webhook 中记录仓库名的属性
在建立新容器前,须要先把旧容器销毁,这里先介绍几个用到的 docker 命令:
docker ps -a -f "name=^docker" --format="{{.Names}}"
查看全部 name 以 docker 开头的 docker 容器,并只输出容器名
docker stop docker-container
中止 name 为 docker-container 的容器
docker rm docker-container
删除 name 为 docker-container 的容器(中止状态的容器才能被删除)
而后给 index.js 添加 docker 相关逻辑
const http = require("http")
const {execSync} = require("child_process")
const fs = require("fs")
const path = require("path")
// 递归删除目录
function deleteFolderRecursive(path) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file) {
const curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
const resolvePost = req =>
new Promise(resolve => {
let chunk = "";
req.on("data", data => {
chunk += data;
});
req.on("end", () => {
resolve(JSON.parse(chunk));
});
});
http.createServer(async (req, res) => {
console.log('receive request')
console.log(req.url)
if (req.method === 'POST' && req.url === '/') {
const data = await resolvePost(req);
const projectDir = path.resolve(`./${data.repository.name}`)
deleteFolderRecursive(projectDir)
// 拉取仓库最新代码
execSync(`git clone https://github.com/yeyan1996/${data.repository.name}.git ${projectDir}`,{
stdio:'inherit',
})
+ // 复制 Dockerfile 到项目目录
+ fs.copyFileSync(path.resolve(`./Dockerfile`), path.resolve(projectDir,'./Dockerfile'))
+ // 复制 .dockerignore 到项目目录
+ fs.copyFileSync(path.resolve(__dirname,`./.dockerignore`), path.resolve(projectDir, './.dockerignore'))
+ // 建立 docker 镜像
+ execSync(`docker build . -t ${data.repository.name}-image:latest `,{
+ stdio:'inherit',
+ cwd: projectDir
+ })
+ // 销毁 docker 容器
+ execSync(`docker ps -a -f "name=^${data.repository.name}-container" --format="{{.Names}}" | xargs -r docker stop | xargs -r docker rm`, {
+ stdio: 'inherit',
+ })
+ // 建立 docker 容器
+ execSync(`docker run -d -p 8888:80 --name ${data.repository.name}-container ${data.repository.name}-image:latest`, {
+ stdio:'inherit',
+ })
+ console.log('deploy success')
res.end('ok')
}
}).listen(3000, () => {
console.log('server is ready')
})
复制代码
在销毁 docker 容器部分用到了 linux 的管道运算符和 xargs
命令,过滤出以 docker-test 开头容器(用 docker-test
仓库的代码制做的镜像建立的容器),中止,删除并从新建立它们
一样经过 scp 复制到云服务器上
scp ./index.js root@118.89.244.45:/root
复制代码
经过以前安装的 pm2 将 index.js 做为后台脚本在云服务器上运行
pm2 start index.js
复制代码
启动成功后,访问云服务器 8888 端口看到部署的 demo 项目(访问前确保服务器已开放 8888 端口)
来试试自动化部署的流程是否能正常运行
首先在云服务器上运行 pm2 logs
查看 index.js 输出的日志,随后本地添加 hello docker
文案,并推送至 github
不出意外,pm2 会输出克隆项目的日志
克隆完毕后将 Dockerfile 和 .dockerignore 放入项目文件中,并更新镜像
接着销毁旧容器,并使用更新后的镜像建立容器
最后访问 8888 端口能够看到更新后的文案
大功告成~
关注 Dockerfile ,.dockerignore, index.js 文件
上述 demo 只建立了单个 docker 容器,当项目更新时,因为容器须要通过销毁和建立的过程,会存在一段时间页面没法访问状况
而实际投入生产时通常会建立多个容器,并逐步更新每一个容器,配合负载均衡将用户的请求映射到不一样端口的容器上,确保线上的服务不会由于容器的更新而宕机
另外基于 github 平台也有很是成熟的 CI/CD 工具,例如
经过 yml 配置文件,简化上文中注册 webhook 和编写更新容器的 index.js 脚本的步骤
# .travis.yml
language: node_js
node_js:
- 8
branchs:
only:
- master
cache:
directories:
- node_modules
install:
- yarn install
scripts:
- yarn test
- yarn build
复制代码
另外随着环境的增多,容器也会逐渐增长,docker 也推出了更好管理多个容器的方式 docker-compose
但本文的宗旨仍是探索其中的原理,维护成熟的开源项目仍是推荐使用上述平台
感谢你能看到这里,但愿对各位有帮助~