得益於 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
但本文的宗旨仍是探索其中的原理,維護成熟的開源項目仍是推薦使用上述平臺
感謝你能看到這裏,但願對各位有幫助~