diff --git a/Dockerfile b/Dockerfile new file mode 100755 index 0000000000000000000000000000000000000000..919fad789831fa8c9efbeebd306f7691ce9d63d2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,33 @@ +#多阶段构建 node基座+镜像源+git拉取+build部分 +FROM node:16-alpine AS build-stage + +# APK包使用阿里的镜像 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories + +#私有仓库账号 注意账户中带@用%40代替 +ARG GIT_USERNAME=帐号 +ARG GIT_PASSWORD=密码 + +RUN apk update && apk add git && git clone https://${GIT_USERNAME}:${GIT_PASSWORD}@gitee.com/gaogao520/xiaoduan-vue-press.git + +WORKDIR xiaoduan-vue-press + +RUN npm config set registry https://registry.npmmirror.com/ && npm install + +RUN npm run docs:build + +# 使用官方的Nginx作为父镜像 +FROM nginx:stable-alpine AS production-stage + +# 复制build后的文件到Nginx的html目录 +COPY --from=build-stage /xiaoduan-vue-press/docs/dist /usr/share/nginx/html + +# 复制自定义的Nginx配置文件 +COPY --from=build-stage /xiaoduan-vue-press/nginx.conf /etc/nginx/conf.d/default.conf + +EXPOSE 5200 + +# docker容器启动时执行的命令 +CMD ["nginx", "-g", "daemon off;"] + + diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d8e161da9fd0c22fab97e2f3aa2fd492ff77544e..0000000000000000000000000000000000000000 --- a/LICENSE +++ /dev/null @@ -1,43 +0,0 @@ -Academic Free License (“AFL”) v. 3.0 - -This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: - -Licensed under the Academic Free License version 3.0 - -1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: - - a) to reproduce the Original Work in copies, either alone or as part of a collective work; - b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; - c) to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor’s reserved rights and remedies, in this Academic Free License; - d) to perform the Original Work publicly; and - e) to display the Original Work publicly. - -2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. - -3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. - -4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor’s trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. - -5) External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). - -6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. - -7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. - -8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. - -9) Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including “fair use” or “fair dealing”). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). - -10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. - -11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. - -12) Attorneys’ Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. - -13) Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. - -14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. - -16) Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/README.md b/README.md index 7d5510af267b15f15fe2c87440068d299aef7ce9..e703828bd13c8c51802986e791589a11aaa55008 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,12 @@ -# Vue、Node等Gitee项目自动化部署到服务器 +# 前端项目使用shell+docker实现简单的自动CICD + +## 背景 +> 代码是托管在[gitee码云](https://gitee.com/)上[私有],没有自建git仓库,其实gitlab和jenkins都可以实现持续[CICD](https://www.digiproto.com/news/255.html), +> 不想给我那小霸王服务器太大的压力以及年底到期想换其他的供应商,为了迁移方便。 + +## 不想自己写 +> 在gitee码云上检索看有小伙伴有没有做过类似的想着改改就能用的那种于是....[原项目地址:https://gitee.com/javanx/webhook](https://gitee.com/javanx/webhook)在原项目基础上新增了docker,在docker中拉取代码、编译,避免服务端环境污染。 + ![](./gitee-webhooks.jpeg) @@ -38,9 +46,10 @@ $ pm2 start webhook.js --name webhook -e ./logs/error.log -o ./logs/out.log 具体的流程大概如下: -- 首先,本地的`vue`项目代码更新之后,通过`git`推送到`Gitee`仓库中。 +- 首先,本地的`vue`项目代码更新之后(理论任何项目),通过`git`推送到`Gitee`仓库中。 - 然后,`Gitee`触发`WebHooks`,即触发相应的钩子,并向服务器发送POST请求。 -- 最后,服务器接收到`Gitee`发送过来的请求后,触发自动化部署脚本,进行拉取代码、重新打包、进行部署。 +- 最后,服务器接收到`Gitee`发送过来的请求后,触发自动化部署脚本,脚本执行dockerfile开始构建dokcer镜像,在镜像中进行拉取代码、重新打包、进行部署。 +- ⚠️:如果重复执行脚本,脚本会先检测容器是否已经存在,如果存在则先停止容器,再删除容器,重新构建镜像,启动容器。 当前,`Gitee`支持的5种类型的钩子,如下: @@ -54,107 +63,14 @@ $ pm2 start webhook.js --name webhook -e ./logs/error.log -o ./logs/out.log 5、评论: 评论仓库、任务、`Pull Request`、`Commit` -由于只需要实现`vue`、`node`项目的自动化部署即可,我这边的话就只选择了`Push`钩子。 - -具体配置如下 - -## 细节解释 -### webhook.js -```javascript -var http = require('http') -var createHandler = require('gitee-webhook-handler') -var handler = createHandler({ path: '/webhook', secret: '123456' }) - -function run_cmd(cmd, args, callback) { - var spawn = require('child_process').spawn; - var child = spawn(cmd, args); - var resp = ""; - child.stdout.on('data', function (buffer) { resp += buffer.toString(); }); - child.stdout.on('end', function () { callback(resp) }); -} - -http.createServer(function (req, res) { - console.log('The server is running at *: 6666') - handler(req, res, function (err) { - res.statusCode = 404 - res.end('no such location') - }) -}).listen(6666) - -handler.on('error', function (err) { - console.error('Error:', err.message) -}) - -handler.on('Push Hook', function (event) { - let pname = event.payload.repository.name - console.log('Received a push event for %s to %s', pname, event.payload.ref); - // pname 是项目名字,和gitee项目名称对应 - console.log(pname, '项目准备构建') - switch (pname) { - // admin项目是vue项目 - case 'admin': - run_cmd('sh', ['./deploy-admin.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置 - break; - // server是node项目 - case 'server': - run_cmd('sh', ['./deploy-server.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置 - break; - } -}) -``` +因为是写的文档类的东西,只需push后能够自动化CICD即可,我这边的话就只选择了`Push`钩子。 -这里启动服务可以通过`http://xxxx.xxx.xxx/6666`进行访问 +# 需要改动的地方 +dockerfile git地址 -### deploy-admin.sh -`admin` 项目执行脚本 +## 细节描述以及文档更新 -```bash -VUE_PATH='/www/wwwroot/admin/' # 项目部署的根目录,需要先通过git clone xxx.git admin是项目名称 - -echo "开始准备构建项目" # 日志打印 -cd $VUE_PATH # cd 到项目根目录 -echo "拉取git最新代码" -git pull # 拉取代码 -echo "npm install 安装最新模块" -# 切换node(暂时不需要) -# nvm use v10.14.1 -# install,避免添加了新的模块而找不到依赖 -npm install # 安装依赖 - -echo "删除dist目录下老版本代码" -# 删除原来的代码 -rm -rf dist/* # 删除原来编译的dist目录 - -echo "npm run build构建项目" -# build -npm run build # 构建项目 - -echo "发布完成" -exit 0; -``` - -### deploy-server.sh -`server` 项目执行脚本 -```bash -VUE_PATH='/www/wwwroot/server/' # 项目部署的根目录,需要先通过git clone xxx.git server是项目名称 - -echo "开始准备构建项目" -cd $VUE_PATH # cd 到项目根目录 -echo "拉取git最新代码" -git pull # 拉取代码 -echo "npm install 安装最新模块" -# 切换node(暂时不需要) -# nvm use v10.14.1 -# install,避免添加了新的模块而找不到依赖 -npm install # 安装依赖 - -echo "pm2 重启项目" -# build -pm2 restart server # pm2 重启项目 - -echo "发布完成" -exit 0; -``` +> http://love.yangzhimao.cn/linux/shell/webhook.html 【就是这个文档站】 ## 相关文章 如果您对pm2、git等不熟悉,可以点击下方文章 diff --git a/deploy-admin.sh b/deploy-admin.sh deleted file mode 100644 index 46be90cc9fa0b89fb38d2ea15deccca2b6ff94e3..0000000000000000000000000000000000000000 --- a/deploy-admin.sh +++ /dev/null @@ -1,22 +0,0 @@ -VUE_PATH='/www/wwwroot/admin/' # 项目部署的根目录,需要先通过git clone xxx.git admin是项目名称 - -echo "开始准备构建项目" # 日志打印 -cd $VUE_PATH # cd 到项目根目录 -echo "拉取git最新代码" -git pull # 拉取代码 -echo "npm install 安装最新模块" -# 切换node(暂时不需要) -# nvm use v10.14.1 -# install,避免添加了新的模块而找不到依赖 -npm install # 安装依赖 - -echo "删除dist目录下老版本代码" -# 删除原来的代码 -rm -rf dist/* # 删除原来编译的dist目录 - -echo "npm run build构建项目" -# build -npm run build # 构建项目 - -echo "发布完成" -exit 0; \ No newline at end of file diff --git a/deploy-server.sh b/deploy-server.sh deleted file mode 100644 index e6a799480fe1169d6118631c576e758a3b0e5fc6..0000000000000000000000000000000000000000 --- a/deploy-server.sh +++ /dev/null @@ -1,18 +0,0 @@ -VUE_PATH='/www/wwwroot/server/' # 项目部署的根目录,需要先通过git clone xxx.git server是项目名称 - -echo "开始准备构建项目" -cd $VUE_PATH # cd 到项目根目录 -echo "拉取git最新代码" -git pull # 拉取代码 -echo "npm install 安装最新模块" -# 切换node(暂时不需要) -# nvm use v10.14.1 -# install,避免添加了新的模块而找不到依赖 -npm install # 安装依赖 - -echo "pm2 重启项目" -# build -pm2 restart server # pm2 重启项目 - -echo "发布完成" -exit 0; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..1a016264e96e8be7ae37a9f1669df6f67a79aeca --- /dev/null +++ b/package-lock.json @@ -0,0 +1,81 @@ +{ + "name": "githook", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "githook", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "gitee-webhook-handler": "^0.1.2" + } + }, + "node_modules/bl": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/bl/-/bl-1.1.2.tgz", + "integrity": "sha512-uVVYHEQk+OuWvCi5U+iquVXvvGCWXKawjwELIR2XMLsqfV/e2sGDClVBs8OlGIgGsStPRY/Es311YKYIlYCWAg==", + "dependencies": { + "readable-stream": "~2.0.5" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "node_modules/gitee-webhook-handler": { + "version": "0.1.2", + "resolved": "https://registry.npmmirror.com/gitee-webhook-handler/-/gitee-webhook-handler-0.1.2.tgz", + "integrity": "sha512-DYNENuxugSf7iM5OrjBPOtTFn/NWdxSYpCWjL8e1+vaxy3xlcVaQ178921e7qHBJYCwTjFZos6uug161KRTdRQ==", + "dependencies": { + "bl": "~1.1.2", + "buffer-equal-constant-time": "~1.0.1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "node_modules/process-nextick-args": { + "version": "1.0.7", + "resolved": "https://registry.npmmirror.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz", + "integrity": "sha512-yN0WQmuCX63LP/TMvAg31nvT6m4vDqJEiiv2CAZqWOGNWutc9DfDk1NPYYmKUFmaVM2UwDowH4u5AHWYP/jxKw==" + }, + "node_modules/readable-stream": { + "version": "2.0.6", + "resolved": "https://registry.npmmirror.com/readable-stream/-/readable-stream-2.0.6.tgz", + "integrity": "sha512-TXcFfb63BQe1+ySzsHZI/5v1aJPCShfqvWJ64ayNImXMsN1Cd0YGk/wm8KB7/OeessgPc9QvS9Zou8QTkFzsLw==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~0.10.x", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmmirror.com/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + } + } +} diff --git a/package.json b/package.json old mode 100644 new mode 100755 index 3d0f46853de1a67aa8139b86bf783464a64cc2d3..04342b357735bf9ebb1d3cb75e6110f311b1bb52 --- a/package.json +++ b/package.json @@ -1,12 +1,13 @@ { - "name": "webhook", + "name": "githook", "version": "1.0.0", "description": "", - "main": "index.js", + "main": "webhook.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "serve": "node webhook" }, - "author": "javan", + "keywords": [], + "author": "", "license": "ISC", "dependencies": { "gitee-webhook-handler": "^0.1.2" diff --git a/sh1.sh b/sh1.sh new file mode 100755 index 0000000000000000000000000000000000000000..1c176a9906b4bb2d7be96cea6f5a865bc13b8769 --- /dev/null +++ b/sh1.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +#获取当前工作目录 +CURRENT_DIR=$(pwd) +#日志文件名 +LOG_FILE_NAME="$(date +'%Y-%m-%d_%H-%M-%S')_logfile.log" +#创建文件 +touch "$LOG_FILE_NAME" +# 定义日志文件路径 +LOG_FILE=${CURRENT_DIR}/${LOG_FILE_NAME} +echo "当前工作目录是: $CURRENT_DIR" >> ${LOG_FILE} +# Shell脚本没有足够的权限 必须root才能执行docker +if [ "$(id -u)" != "0" ]; then + echo " 此脚本必须以root用户身份运行 " >> ${LOG_FILE} + exit 1 +fi +which git >> ${LOG_FILE} +git --version >> ${LOG_FILE} +docker --version >> ${LOG_FILE} +# 检测docker是否在运行 开始 +docker_status=$(systemctl is-active docker) + +if [ "$docker_status" = "active" ]; then + echo "Docker 服务正在运行" >> ${LOG_FILE} +else + echo "Docker 服务没有运行" >> ${LOG_FILE} +fi +# 检测docker是否在运行 结束 +echo "-------------------删除容器前 $(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} +docker image ls >> ${LOG_FILE} + +# 删除容器操作 容器名称或ID 也是后面操作构建的镜像名容器启动名 +CONTAINER_NAME="web_vuepress_v2" + +# 检查容器是否在运行 +function is_container_running { + local container_name=$1 + docker ps --format '{{.Names}}' | grep -q "^${container_name}$" +} + +# 停止并删除容器 +function stop_and_remove_container { + local container_name=$1 + if is_container_running "$container_name"; then + echo "容器 $container_name 正在运行,将停止并删除它...$(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} + docker stop "$container_name" + docker rm "$container_name" + echo "容器 $container_name 已停止并删除。$(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} + else + echo "容器 $container_name 不在运行或不存在。$(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} + fi +} + +# 调用函数来停止并删除容器 +stop_and_remove_container "$CONTAINER_NAME" + +echo "-------------------构建镜像开始 $(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} +#dockerfile 必须和脚本在同路径下 docker重复构建会新会覆盖旧 +docker build --no-cache -t $CONTAINER_NAME:tag . >> ${LOG_FILE} +echo "-------------------构建镜像结束 $(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} +docker image ls >> ${LOG_FILE} +echo "-------------------启动容器前 $(date +'%Y-%m-%d %H:%M:%S')" >> ${LOG_FILE} +#启动容器 容器名 容器内部5200端口映射到物理机5201端口 启动的镜像名也可以是镜像id +docker run -itd --name run_$CONTAINER_NAME -p 5201:5200 $CONTAINER_NAME:tag >> ${LOG_FILE} diff --git a/webhook.js b/webhook.js old mode 100644 new mode 100755 index 59384eb7a2ad108b39efc734e11dd305289ee4bc..bdd5d3c6ba7add33a3a5c75b94516ccad0e09a83 --- a/webhook.js +++ b/webhook.js @@ -4,35 +4,55 @@ var handler = createHandler({ path: '/webhook', secret: '123456' }) function run_cmd(cmd, args, callback) { var spawn = require('child_process').spawn; - var child = spawn(cmd, args); + var child = spawn(cmd, args, + { + stdio: ['inherit', 'pipe', 'pipe'] // 继承标准输出,但捕获标准错误 + }); var resp = ""; - child.stdout.on('data', function (buffer) { resp += buffer.toString(); }); - child.stdout.on('end', function () { callback(resp) }); + child.stdout.on('data', function (buffer) { + console.log(`stdout: ${buffer}`); + resp += buffer.toString(); + }); + child.stdout.on('end', function () { + console.log(`stdout:end `); + callback(resp); + + }); + child.stdout.on('error', (err) => { + console.error('An error occurred while running the subprocess:', err); + }); } http.createServer(function (req, res) { - console.log('The server is running at *: 6666') + console.log('请求进入') handler(req, res, function (err) { res.statusCode = 404 res.end('no such location') }) -}).listen(6666) +}).listen(5200, () => { + console.log('The server is running at *: 5200') +}) handler.on('error', function (err) { console.error('Error:', err.message) }) +handler.on('push_hooks', function (event) { + console.log("测试 push_hooks") + run_cmd('sh', ['-c', 'bash sh1.sh'], function (text) { console.log(text) }); +}) handler.on('Push Hook', function (event) { + console.log("正式 Push Hook") let pname = event.payload.repository.name console.log('Received a push event for %s to %s', pname, event.payload.ref); // pname 是项目名字,和gitee项目名称对应 console.log(pname, '项目准备构建') switch (pname) { // admin项目是vue项目 - case 'admin': - run_cmd('sh', ['./deploy-admin.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置 + case 'xiaoduanVuePress': + run_cmd('sh', ['./sh1.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置 break; - // server是node项目 + // server是 其他项目 case 'server': run_cmd('sh', ['./deploy-server.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置 break;