白嫖 Coding,部署 CI/CD 流水线

需求

Coding 的自动部署仅支持 K8S pod,但是个人项目实际上用不上这么复杂的玩意儿,所以写一个 docker compose 的部署脚本就好

大致的思路:

  1. 写一个部署脚本,开放一个端口
  2. 在 Coding 流水线的最后通过 shell 命令 curl 一下访问这个地址即可

如果你熟悉 AI 的话,可以直接问 AI 写一个部署脚本即可

前置需求

先参考这个文章,将你的项目 docker 化

https://flands.com/2022/04/12/52.CICD/

部署一个 Nginxproxymanager 管理工具

Coding 工作

依旧是 Coding 流水线,最后面添加一个执行部署脚本

1
2
3
4
#!/bin/bash

curl -X GET \
"https://xxxx.cn/deploy"

部署脚本

目录下创建 Logs 文件夹,新建 packages.json 文件,执行 npm init

1
2
3
4
5
6
{
"dependencies": {
"express": "^5.1.0",
"winston": "^3.17.0"
}
}

新建 index.js 文件

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const express = require('express');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const winston = require('winston');

// 创建日志目录
const logDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}

// 配置日志
const logger = winston.createLogger({
levels: winston.config.npm.levels,
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
),
transports: [
new winston.transports.File({
filename: path.join(logDir, 'info.log'),
level: 'info'
}),
new winston.transports.File({
filename: path.join(logDir, 'error.log'),
level: 'error'
}),
new winston.transports.Console({
level: 'debug',
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
})
],
exitOnError: false
});

const app = express();
const PORT = 5002;

app.get('/deploy', (req, res) => {
const dockerImage = 'xxxx:latest'; // 替换为你的 Docker 镜像名称
const dockerComposeFilePath = path.join('xxxx/docker-compose.yml'); // 替换为你的 docker-compose 文件路径
// 执行 docker pull 命令
exec(`docker pull ${dockerImage}`, (err, stdout, stderr) => {
if (err) {
logger.error(`Docker pull error: ${err}`);
return res.status(500).send('Docker pull failed');
}
logger.info(`Docker pull stdout: ${stdout}`);
logger.error(`Docker pull stderr: ${stderr}`);

// 执行 docker-compose up -d 命令
exec(`docker compose -f ${dockerComposeFilePath} up -d`, (err, stdout, stderr) => {
if (err) {
logger.error(`Docker-compose up error: ${err}`);
return res.status(500).send('Docker-compose up failed');
}
logger.info(`Docker-compose up stdout: ${stdout}`);
logger.error(`Docker-compose up stderr: ${stderr}`);
res.send('Deployment successful');
});
});
});

app.listen(PORT, () => {
logger.info(`Server is running on http://localhost:${PORT}`);
});

安装 PM2,启动这个脚本,然后在 nginx 管理器中能访问这个地址就好