前言
得益于 node 的橫空出世以及前端工程化的興起,無論是開發(fā)模式,還是開發(fā)框架,前端生態(tài)鏈都產(chǎn)生了翻天覆地的變化,與此同時(shí)前端慢慢開始向其他領(lǐng)域探索,項(xiàng)目部署就是其中一個(gè)領(lǐng)域
在刀耕火種的時(shí)代,當(dāng)執(zhí)行 npm run build
將生成產(chǎn)物交給運(yùn)維后,前端的任務(wù)就算完成了,運(yùn)維同學(xué)在生產(chǎn)服務(wù)器上將產(chǎn)物的路徑寫入 nginx 配置文件,至此完成了“簡(jiǎn)單”的部署
隨著項(xiàng)目的不斷迭代,前端開始發(fā)現(xiàn)問題的嚴(yán)重性,每次都需要耗費(fèi)大量的時(shí)間在打包上,開發(fā)5分鐘,打包半小時(shí)的情況屢見不鮮
,另外開發(fā)者自身環(huán)境的差異會(huì)導(dǎo)致最終的產(chǎn)物也有不同
但辦法總比困難多,例如可以將打包操作放到遠(yuǎn)端服務(wù)器上,又比如可以將上述流程結(jié)合 git 倉庫實(shí)現(xiàn)自動(dòng)部署
本著不設(shè)邊界的“字節(jié)范”,本文將從零開始,實(shí)現(xiàn)前端自動(dòng)化部署流程,打開項(xiàng)目部署的“黑盒”
涉及技術(shù)棧如下:
docker
node
pm2
shell
webhook
文章中的命令大部分為 linux 命令,本地是 windows 系統(tǒng)的讀者請(qǐng)使用 git bash
介紹 docker
著手開發(fā)前,先介紹這次的主角 docker
什么是 docker
簡(jiǎn)而言之,docker 可以靈活的創(chuàng)建/銷毀/管理多個(gè)“服務(wù)器”,這些“服務(wù)器”被稱為 容器 (container)
在容器中你可以做任何服務(wù)器可以做的事,例如在有 node 環(huán)境的容器中運(yùn)行 npm run build
打包項(xiàng)目,在有 nginx 環(huán)境的容器中部署項(xiàng)目,在有 mysql 環(huán)境的容器中做數(shù)據(jù)存儲(chǔ)等等
一旦服務(wù)器安裝了 docker ,就可以自由創(chuàng)建任意多的容器,上圖中 docker 的 logo 形象的展示了它們之間的關(guān)系,??就是 docker,上面的一個(gè)個(gè)集裝箱就是容器
安裝 docker
為了方便本地調(diào)試,可以先在本地安裝 docker
Mac:https://download.docker.com/mac/stable/Docker.dmg
Windows:https://download.docker.com/win/stable/Docker%20for%20Windows%20Installer.exe
Linux:https://get.docker.com/
下載安裝完畢后,點(diǎn)擊 docker 圖標(biāo)啟動(dòng) docker,此時(shí)在終端中就可以使用 docker 相關(guān)的操作
出現(xiàn)以下情況,檢查 docker 應(yīng)用程序是否正常啟動(dòng)
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n36" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" cid="n58" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">
<h1>Hello docker</h1></pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="dockerfile" cid="n59" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"># Dockerfile
FROM nginx
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 80</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n69" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">hello-docker
|____index.html
|____Dockerfile</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n72" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">docker build . -t test-image:latest </pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n85" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">docker run -d -p 80:80 --name test-container test-image:latest</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n102" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">docker pull nginx
docker run -d -p 81:80 --name nginx-container nginx</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n155" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">less ~/.ssh/id_rsa.pub </pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n158" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">$ 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</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n159" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaCxxxxxxxxxxxxxxxxxxxxxxxxBWDSU
GPl+nafzlHDTYxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxPppSwg0cda3
Pbv7kOdJ/MxxxxxxxxxxxxxxxxxxxxxxxxxxxQwdsdMFvSlVK/7XA
t3FaoJoxxxxxxxxxxxxxxxxxxxxx88XypNDvjYNby6vw/Pb0rwert/En
mZ+AW4OZPnTxxxxxxxxxxxxxxxxxxo1d01QraTlMqVSsbx
NrRFi9wrf+M7Q== schacon@mylaptop.local</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n164" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">ssh <username>@<hostname or IP address></pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n170" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"># Step 1: 安裝必要的一些系統(tǒng)工具
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服務(wù)
sudo systemctl docker start
Step 5: 運(yùn)行 hello-world 項(xiàng)目
sudo docker run hello-world</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n174" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">yum install git</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n179" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n181" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">export NVM_DIR="NVM_DIR/nvm.sh" ] && . "
NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion" # This loads nvm bash_completion</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n183" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">nvm install node</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n186" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">npm i pm2 -g</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n190" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">vue create docker-test</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="dockerfile" cid="n213" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"># dockerfile
build stage
FROM node:latest as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
?
production stage
FROM nginx:latest as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n240" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">scp ./Dockerfile root@118.89.244.45:/root</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n244" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"># .dockerignore
node_modules</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n249" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">scp ./.dockerignore root@118.89.244.45:/root</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n253" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">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')
})</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="diff" cid="n256" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">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')
})</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="diff" cid="n270" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">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',
})
// 復(fù)制 Dockerfile 到項(xiàng)目目錄
fs.copyFileSync(path.resolve(`./Dockerfile`), path.resolve(projectDir,'./Dockerfile'))
?
// 復(fù)制 .dockerignore 到項(xiàng)目目錄
fs.copyFileSync(path.resolve(__dirname,`./.dockerignore`), path.resolve(projectDir, './.dockerignore'))
?
// 創(chuàng)建 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',
- })
? // 創(chuàng)建 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')
})</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n272" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">scp ./index.js root@118.89.244.45:/root</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="shell" cid="n275" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;">pm2 start index.js</pre>
-
通過 yml 配置文件,簡(jiǎn)化上文中注冊(cè) webhook 和編寫更新容器的 index.js 腳本的步驟
imageimage<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="yml" cid="n305" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.714285em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"># .travis.yml
language: node_js
node_js:- 8
branchs:
only: - master
cache:
directories: - node_modules
install: - yarn install
scripts: - yarn test
- yarn build</pre>
Best practices for writing Dockerfiles
參考資料
感謝你能看到這里,希望對(duì)各位有幫助~
但本文的宗旨還是探索其中的原理,維護(hù)成熟的開源項(xiàng)目還是推薦使用上述平臺(tái)
image另外隨著環(huán)境的增多,容器也會(huì)逐漸增加,docker 也推出了更好管理容器的方式 docker-compose
- 8
基于 github 平臺(tái)也有非常成熟的 CI/CD 工具,例如
寫在后面
關(guān)注 Dockerfile ,.dockerignore, index.js 文件
源碼
大功告成~
最后訪問 8888 端口可以看到更新后的文案
接著銷毀舊容器,并使用更新后的鏡像創(chuàng)建容器
克隆完畢后將 Dockerfile 和 .dockerignore 放入項(xiàng)目文件中,并更新鏡像
不出意外,pm2 會(huì)輸出克隆項(xiàng)目的日志
首先在云服務(wù)器上運(yùn)行 pm2 logs
查看 index.js 輸出的日志,隨后本地添加 hello docker
文案,并推送至 github
來試試自動(dòng)化部署的流程是否能正常運(yùn)行
try it
啟動(dòng)成功后,訪問云服務(wù)器 8888 端口看到部署的 demo 項(xiàng)目
通過之前安裝的 pm2 將 index.js 作為后臺(tái)腳本在云服務(wù)器上運(yùn)行
運(yùn)行 node 腳本
同樣通過 scp 復(fù)制到云服務(wù)器上
然后給 index.js 添加 docker 相關(guān)邏輯
刪除 name 為 docker-container 的容器(停止?fàn)顟B(tài)的容器才能被刪除)
docker rm docker-container
停止 name 為 docker-container 的容器
docker stop docker-container
查看所有 name 以 docker 開頭的 docker 容器,并只輸出容器名
docker ps -a -f "name=^docker" --format="{{.Names}}"
在創(chuàng)建新容器前,需要先把舊容器銷毀,這里先介紹幾個(gè)用到的 docker 命令:
創(chuàng)建鏡像和容器
data.repository.name
即 webhook 中記錄倉庫名的屬性
當(dāng)項(xiàng)目更新后,云服務(wù)器需要先拉取倉庫最新代碼
拉取倉庫代碼
本地項(xiàng)目里新建 index.js
由于我們是前端開發(fā),這里使用 node 開啟一個(gè)簡(jiǎn)單的 http 服務(wù)器處理 webhook 發(fā)送的 post 請(qǐng)求
創(chuàng)建 http 服務(wù)器
接著將 .dockerignore 文件也復(fù)制到云服務(wù)器上
第二次復(fù)制除 node_modules的所有文件
第一次只復(fù)制 package.json 和 package-lock.json,并安裝依賴
由于需要保持本地和容器中 node_module 依賴包一致,在創(chuàng)建 Dockerfile 時(shí)用了兩次 COPY
命令
本地項(xiàng)目里新建 .dockerignore
類似 .gitignore,.dockerignore 可以在創(chuàng)建鏡像復(fù)制文件時(shí)忽略復(fù)制某些文件
創(chuàng)建 .dockerignore
最后通過 scp
命令,將 Dockerfile 文件復(fù)制到云服務(wù)器上
FROM nginx:latest as production-stage:基于 nginx 最新鏡像,并將有 nginx 環(huán)境的階段命名為
production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html:通過 --form 參數(shù)可以引用
build-stage
階段生成的產(chǎn)物,將其復(fù)制到 /usr/share/nginx/htmlEXPOSE 80:容器對(duì)外暴露 80 端口
CMD ["nginx", "-g", "daemon off;"]:容器創(chuàng)建時(shí)運(yùn)行
nginx -g daemon off
命令,一旦 CMD 對(duì)應(yīng)的命令結(jié)束,容器就會(huì)被銷毀
,所以通過 daemon off 讓 nginx 一直在前臺(tái)運(yùn)行
將構(gòu)建分為兩個(gè)階段,第一階段基于 node 鏡像,第二階段基于 nginx 鏡像
這里用到了 docker 一個(gè)技巧:多階段構(gòu)建
FROM node:latest as build-stage:基于 node 最新鏡像,并通過構(gòu)建階段命名,將有 node 環(huán)境的階段命名為
build-stage
WORKDIR /app:將工作區(qū)設(shè)為 /app,和其他系統(tǒng)文件隔離
COPY package*.json ./:拷貝 package.json/package-lock.json 到容器的 /app 目錄
RUN npm install:運(yùn)行
npm install
在容器中安裝依賴COPY . .:拷貝其他文件到容器 /app 目錄,分兩次拷貝是因?yàn)楸3?node_modules 一致
RUN npm run build:運(yùn)行
npm run build
在容器中構(gòu)建
逐行解析配置:
先在本地項(xiàng)目里新建一個(gè) Dockerfile 用于之后創(chuàng)建鏡像
創(chuàng)建 Dockerfile
當(dāng)云服務(wù)器接收到項(xiàng)目更新后發(fā)送的 post 請(qǐng)求后,需要?jiǎng)?chuàng)建/更新鏡像來實(shí)現(xiàn)自動(dòng)化部署
處理項(xiàng)目更新的請(qǐng)求
參數(shù)主要涉及當(dāng)前倉庫和本地提交的信息,這里我們只用 repository.name
獲取更新的倉庫名即可
配置完成后,可以向倉庫提交一個(gè) commit,然后點(diǎn)擊最下方可以看到 post 請(qǐng)求參數(shù)
測(cè)試 webhook
點(diǎn)擊 Add webhook
為當(dāng)前項(xiàng)目添加一個(gè) webhook,至此,當(dāng) docker-test
項(xiàng)目有代碼提交時(shí),就會(huì)往 http://118.89.244.45:3000
發(fā)送一個(gè) post 請(qǐng)求
webhook 還可以設(shè)置一些鑒權(quán)相關(guān)的 token,由于是個(gè)人項(xiàng)目這里不詳細(xì)展開了
觸發(fā)時(shí)機(jī):Just the push event,即倉庫 push 事件,根據(jù)不同的需求還可以選擇其他事件,例如 PR,提交 Commit,提交 issues 等
Content type:選擇 application/json 即發(fā)送 json 格式的 post 請(qǐng)求
Payload URL:填寫云服務(wù)器公網(wǎng) IP,記得添加 http(s) 前綴
打開 github 的倉庫主頁,點(diǎn)擊右側(cè) settings
配置 webhook
當(dāng)倉庫有提交代碼時(shí),通過將 webhook 請(qǐng)求地址指向云服務(wù)器 IP 地址,云服務(wù)器就能知道項(xiàng)目有更新,之后運(yùn)行相關(guān)代碼實(shí)現(xiàn)自動(dòng)化部署
參考 Vue 生命周期,當(dāng)組件掛載完成時(shí)會(huì)觸發(fā) mounted 鉤子,在鉤子中可以編寫拉取后端數(shù)據(jù),或者渲染頁面等回調(diào)邏輯,而 github 的 webhook 會(huì)在當(dāng)前倉庫觸發(fā)某些事件時(shí),發(fā)送一個(gè) post 形式的 http 請(qǐng)求
hook 翻譯為“鉤子”,還可以理解為“回調(diào)”
webhook
并將 demo 項(xiàng)目上傳到 github,準(zhǔn)備配置 webhook
簡(jiǎn)單使用 vue-cli 在本地創(chuàng)建項(xiàng)目
創(chuàng)建 demo 項(xiàng)目
node 安裝完成后,還需要安裝 pm2
,它能使你的 js 腳本能在云服務(wù)器的后臺(tái)運(yùn)行
通過 nvm 安裝最新版 node
將 nvm 作為環(huán)境變量
既然是前端自動(dòng)化部署,云服務(wù)器上相關(guān)處理邏輯用 js 編寫,所以需要安裝 node 環(huán)境,這里用 nvm 來管理 node 版本
node
由于 SSH 方式還需要在 github 上注冊(cè)公鑰,方便起見,之后會(huì)選擇 HTTPS 的方式克隆倉庫
自動(dòng)化部署涉及到拉取最新的代碼,所以需要安裝 git 環(huán)境
git
彈出 Hello from Docker!
證明 Docker 已經(jīng)成功安裝啦~
云服務(wù)器安裝和本地有些區(qū)別,根據(jù) docker 官網(wǎng) 的安裝教程,運(yùn)行以下命令
之前在本地安裝了 docker,但云服務(wù)器上默認(rèn)也是沒有的,所以需要給它也安裝 docker 環(huán)境
docker
接著給云服務(wù)器安裝基礎(chǔ)的環(huán)境
安裝環(huán)境
綁定完成后重新開機(jī),至此就可以在本地通過 ssh 命令登陸云服務(wù)器啦
除了注冊(cè)公鑰,還需要將它綁定實(shí)例,將實(shí)例關(guān)機(jī)并進(jìn)行綁定
將生成的公鑰放在云服務(wù)器控制臺(tái)圖示部分,點(diǎn)擊確定
沒有生成過密鑰本地運(yùn)行以下命令即可,參考 服務(wù)器上的 Git - 生成 SSH 公鑰
生成密鑰的方式同 git,之前生成過的話本地執(zhí)行以下命令就能查看
前者無需配置,但每次登陸都需要輸入賬號(hào)密碼,后者需要注冊(cè) ssh 密鑰,但之后可以免密登陸云服務(wù)器。個(gè)人比較喜歡后者,所以先在控制臺(tái)注冊(cè) ssh 密鑰然后我們需要登陸云服務(wù)器,本地登陸云服務(wù)器的方式一般有兩種,密碼登陸和 ssh 登陸(或者用 ssh 工具,windows 系統(tǒng)可以用 xhell,macOS 可以用 putty)
公網(wǎng) IP 用于之后 webhook 發(fā)送請(qǐng)求的地址
注冊(cè)相關(guān)的操作不細(xì)說了,參考供應(yīng)商教程,隨后登陸控制臺(tái)可以看到當(dāng)前云服務(wù)器的公網(wǎng) IP,例如下圖中服務(wù)器的公網(wǎng) IP 是:118.89.244.45
熟悉云服務(wù)器配置或者不是騰訊云的讀者可以跳過這章
登陸云服務(wù)器
由于是個(gè)人項(xiàng)目,對(duì)云服務(wù)器的要求不高,大部分供應(yīng)商會(huì)給新用戶白嫖免費(fèi)試用 1-2 周,這里我選擇騰訊云 CentOS 7.6 64位
的操作系統(tǒng),當(dāng)然阿里云或其他云服務(wù)器也完全 ok
首先你得有一臺(tái)服務(wù)器吧-。-
云服務(wù)器
可以發(fā)現(xiàn),實(shí)現(xiàn)前端自動(dòng)化部署后開發(fā)者需要做的只是把代碼推到倉庫,其余的事都可以通過服務(wù)器上的自動(dòng)化腳本完成
git push
提交代碼到倉庫服務(wù)器自動(dòng)更新鏡像
鏡像中自動(dòng)運(yùn)行
npm run build
生成構(gòu)建產(chǎn)物服務(wù)器自動(dòng)創(chuàng)建容器
在實(shí)現(xiàn)前端自動(dòng)化部署后:
本地運(yùn)行
npm run build
生成構(gòu)建產(chǎn)物將產(chǎn)物通過 ftp 等形式上傳到服務(wù)器
git push
提交代碼到倉庫
在沒遷移 Docker 之前,若我想更新線上網(wǎng)站中內(nèi)容時(shí),需要:
介紹完 docker,接著我們從零開始實(shí)現(xiàn)前端自動(dòng)化部署
前端自動(dòng)化部署
相比于真實(shí)服務(wù)器/虛擬機(jī),容器不包含操作系統(tǒng),這意味著創(chuàng)建/銷毀容器都十分高效
高效并節(jié)省資源
使用 docker 可以使你的服務(wù)器更干凈,構(gòu)建用到的環(huán)境可以都放在容器中
環(huán)境隔離
在創(chuàng)建鏡像時(shí)可以使用 tag 標(biāo)記版本,如果某個(gè)版本的環(huán)境有問題,可以快速回滾到之前版本
類似 git,docker 也有版本控制
便于回滾
服務(wù)器拉取賬號(hào) yeyan1996
下的 docker-test-image
鏡像
docker pull yeyan1996/docker-test-image:latest
本地提交名為 docker-test-image
的鏡像,鏡像名需要加上 dockerhub 賬號(hào)作為前綴
docker push yeyan1996/docker-test-image:latest
開發(fā)者可以將開發(fā)環(huán)境用 docker 鏡像上傳到 docker 倉庫,在生產(chǎn)環(huán)境拉取并運(yùn)行相同的鏡像,保持環(huán)境一致
docker 的出現(xiàn)解決了一個(gè)世紀(jì)難題:在我電腦上明明是好的
:)
環(huán)境統(tǒng)一
有人會(huì)問,環(huán)境我都可以裝在自己的服務(wù)器上,為什么還要放在一個(gè)個(gè)容器里呢?這里列舉使用 docker 的幾個(gè)優(yōu)點(diǎn)
了解了 docker 的概念和使用方法,接著講講為什么要用 docker
為什么要用 docker
由于上一步操作本地 80 端口已經(jīng)被占用了,這里使用 81 端口映射到容器的 80 端口,訪問 localhost:81
可以看到 nginx 啟動(dòng)頁面
第一步拉取了官方的 nginx 鏡像,第二步用基于官方 nginx 鏡像創(chuàng)建名為 nginx-container
的容器
開發(fā)者可以將 Dockerfile 生成的鏡像上傳到 dockerhub 來存儲(chǔ)自定義鏡像,也可以直接使用官方提供的鏡像
如果說 github 是存儲(chǔ)代碼的倉庫,那么 dockerhub 就是存儲(chǔ)鏡像的倉庫
DockerHub
由于本地 80 端口映射到了容器的 80 端口,所以當(dāng)輸入 localhost
時(shí),會(huì)顯示 index.html 文件內(nèi)容
run:創(chuàng)建并運(yùn)行 docker 容器
-d: 后臺(tái)運(yùn)行容器
80:80:將當(dāng)前服務(wù)器的 80 端口(冒號(hào)前的 80),映射到容器的 80 端口(冒號(hào)后的 80)
--name:給容器命名,便于之后定位容器
test-image:latest:基于
test-image
最新版本的鏡像創(chuàng)建容器
鏡像成功創(chuàng)建后,運(yùn)行以下命令可以創(chuàng)建一個(gè) docker 容器
創(chuàng)建容器
build:創(chuàng)建 docker 鏡像
.:使用當(dāng)前目錄下的 dockerfile 文件
-t:使用 tag 標(biāo)記版本
test-image:latest:創(chuàng)建名為
test-image
的鏡像,并標(biāo)記為 latest(最新)版本
在創(chuàng)建 Dockerfile 文件后,在當(dāng)前目錄運(yùn)行以下命令可以創(chuàng)建一個(gè) docker 鏡像
創(chuàng)建鏡像
此時(shí),你的文件結(jié)構(gòu)應(yīng)該是
其他 Dockerfile 配置參考官方文檔
FROM nginx:基于官方 nginx 鏡像
COPY index.html /usr/share/nginx/html/index.html:將當(dāng)前目錄下 index.html 替換容器中 /usr/share/nginx/html/index.html 文件,
/usr/share/nginx/html
是 nginx 默認(rèn)存放網(wǎng)頁文件的目錄,訪問容器 80 端口會(huì)展示該目錄下 index.html 文件EXPOSE 80:容器對(duì)外暴露 80 端口,主要起聲明作用,真實(shí)端口映射還需要在創(chuàng)建容器時(shí)定義
首先創(chuàng)建一個(gè) hello-docker
目錄,在目錄中創(chuàng)建 index.html
和 Dockerfile
文件
創(chuàng)建文件
嘗試用 Dockerfile 創(chuàng)建 docker 鏡像
Dockerfile 是一個(gè)配置文件,類似 .gitlab-ci.yml/package.json,定義了如何生成鏡像
Dockerfile
Dockerfile 文件創(chuàng)建而成
直接使用 DockerHub 或者其他倉庫上現(xiàn)有的鏡像
有兩種方式獲取鏡像
如果把容器比作輕量的服務(wù)器,那么鏡像就是創(chuàng)建它的模版,一個(gè) docker 鏡像可以創(chuàng)建多個(gè)容器,它們的關(guān)系好比 JavaScript 中類和實(shí)例的關(guān)系
鏡像(image)
容器(container)
倉庫(repository)
docker 有三個(gè)重要的概念