示例
好的,下面我们以一个简单的 Node.js 应用为例,详细展示如何实现一个完整的 CI/CD 流程。包括代码库的配置、CI/CD 工具的使用以及自动化构建、测试和部署。
1. 初始化项目
首先,创建一个简单的 Node.js 项目。
mkdir my-node-app
cd my-node-app
npm init -y
npm install express创建一个简单的 server.js 文件:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});2. 配置测试
安装 Jest 作为测试框架:
npm install jest --save-dev在 package.json 中添加测试脚本:
"scripts": {
"test": "jest"
}创建一个简单的测试文件 app.test.js:
const request = require('supertest');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
describe('GET /', () => {
it('responds with Hello World!', done => {
request(app)
.get('/')
.expect('Hello World!', done);
});
});3. 配置 GitHub Actions
在项目根目录下创建 .github/workflows 目录,并在其中创建 ci.yml 文件:
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test4. 配置 GitLab CI/CD
如果你使用的是 GitLab,可以创建一个 .gitlab-ci.yml 文件:
stages:
- build
- test
- deploy
build:
stage: build
script:
- npm install
- npm run build
test:
stage: test
script:
- npm test
deploy:
stage: deploy
script:
- echo "Deploying to production server"
- npm run deploy
only:
- main5. 自动部署
在 GitHub Actions 或 GitLab CI/CD 中配置部署步骤。
GitHub Actions 自动部署
在 ci.yml 文件中添加部署步骤:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
- name: Deploy
run: |
echo "Deploying to production server"
npm run deploy
env:
DEPLOYMENT_KEY: ${{ secrets.DEPLOYMENT_KEY }}6. 持续监控
部署后,可以使用监控工具来监控应用的运行状态。
Prometheus 和 Grafana 配置
- 安装 Prometheus:
docker run -d --name=prometheus -p 9090:9090 prom/prometheus- 安装 Grafana:
docker run -d --name=grafana -p 3000:3000 grafana/grafana- 配置 Prometheus:
在
prometheus.yml文件中添加抓取目标(如你的应用):
scrape_configs:
- job_name: 'my-node-app'
static_configs:
- targets: ['localhost:3000']- 配置 Grafana:
- 打开 Grafana,添加 Prometheus 作为数据源。
- 创建仪表板,添加你需要监控的指标。 通过以上步骤,你可以创建一个完整的 CI/CD 流程,包括代码提交、自动化测试、自动化部署以及持续监控,确保你的应用始终处于最佳状态。