react项目和node项目部署-docker+nginx持续集成
kingcwt2023-06-01前端docker nginx 持续集成
- 在github新建3个项目分别为react-front,react-back,react-webhook 【均为demo项目】
前端:react-front项目
项目用什么创建无所谓 但是需要配置Dockerfile和nginx到你的项目根目录
- 配置Dockerfile
# 配置Dockerfile
FROM nginx
LABEL name='react-front'
LABEL version='1.0'
COPY ./dist /usr/share/nginx/html
COPY ./react-front.conf /etc/nginx/conf.d
EXPOSE 80
- 配置nginx
# 配置 react-front.conf
server {
listen 80;
server_name 这里输入你的服务器公网ip即可;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://你的服务器公网ip:3000/api;
}
}
后端: react-back项目
这里用node原生写一个后端服务,需要配置Dockerfile
- 配置Dockerfile
FROM node
LABEL name='react-back'
LABEL version='1.0.0'
COPY . /app
WORKDIR /app
RUN npm install
CMD npm start
EXPOSE 3000
- server.js
// 后端服务
let http = require('http');
let data = [
{
name: 'Calvin Hawkins',
email: 'calvin.hawkins@example.com',
image:
'https://images.unsplash.com/photo-1491528323818-fdd1faba62cc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
},
{
name: 'Kristen Ramos',
email: 'kristen.ramos@example.com',
image:
'https://images.unsplash.com/photo-1550525811-e5869dd03032?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
},
{
name: 'Ted Fox',
email: 'ted.fox@example.com',
image:
'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
},
{
name: 'c1',
email: 'c1.com',
image:
'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
},
{
name: 'chr1',
email: 'chr1.com',
image:
'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
},
]
let server = http.createServer(function (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
if (req.url === '/api/list') {
res.end(JSON.stringify(data))
} else {
res.end('Not Found')
}
}
)
server.listen(3000,()=>{
console.log('server is running 3000')
});
配置github
接下来在你的github前端项目和后端项目中 设置webhook,前后端都要配置webhook 当你提交代码时 去触发它
1 打开github仓库的前端和后端项目的Settings
- 图1
- 图2
react-webhook项目
此项目主要写一些脚本和服务 前后端提交代码时候 都会触发你配置的/webhook服务
- 配置 react-front.sh
这里主要是配置前端的脚本
#!/bin/bash
WORK_PATH='/usr/projects/react-front'
cd $WORK_PATH
echo "清除老代码"
git reset --hard origin/master
git clean -f
echo "拉取最新代码"
git pull
echo "更新依赖"
npm install
echo "编译"
npm run build
echo "开始构建"
docker build -t react-front:1.0 .
echo "停止旧容器并删除旧容器"
docker stop react-front-container
docker rm react-front-container
echo "启动新容器"
docker container run -p 80:80 --name react-front-container -d react-front:1.0
- 配置react-back.sh
这里主要配置后端的脚本
WORK_PATH='/usr/projects/react-back'
cd $WORK_PATH
echo "清除老代码"
git reset --hard origin/master
git clean -f
echo "拉取最新代码"
git pull
echo "开始构建"
docker build -t react-back:1.0 .
echo "停止旧容器并删除旧容器"
docker stop react-back-container
docker rm react-back-container
echo "启动新容器"
docker container run -p 3000:3000 --name react-back-container -d react-back:1.0
- sendMail.js
此js主要是为了你提交代码成功后 发送一个邮件给到你
// 你需要安装一下 nodemailer
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
service:'qq',
port:465, //SMTP
secureConnection:true, // 使用SSL
auth:{
user:'1003835955@qq.com',
pass:'' // 授权码 在你的邮箱设置里面 SMTP
}
})
function sendMail(message){
let mailOptions = {
from: '1003835955@qq.com', // 发送地址
to:'邮箱', // 接受者
subject:"部署通知", // 主题
html:message // 内容主题
};
transporter.sendMail(mailOptions,(error,info)=>{
if(error){
return console.log(error)
}
console.log('Message send:%s',info.messageId);
})
}
module.exports = sendMail;
- webhook.js
这个是主要react-webhook主要配置内容 当前后端提交代码时 会触发/webhook 然后根据项目名称执行不同的sh脚本 最后更新成功后 发送部署邮箱信息到你的邮箱
let http = require('http');
let crypto = require('crypto');
let { spawn } = require('child_process');
let SECRET = '你webhook设置的密码';
const sendMail = require('./sendMail');
function sign(body) {
return `sha1=` + crypto.createHmac('sha1', SECRET).update(body).digest('hex');
}
let server = http.createServer((req, res) => {
console.log(req.method, req.url, 'req.method, req.url')
if (req.method === 'POST' && req.url === '/webhook') {
let buffers = [];
req.on('data', function (buffer) {
buffers.push(buffer);
});
req.on('end', function (buffer) {
let body = Buffer.concat(buffers);
let event = req.headers['x-github-event'];
let signature = req.headers['x-hub-signature'];
if (signature !== sign(body)) {
res.end('Not Allowed');
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ ok: true }));
if (event === 'push') {
let payload = JSON.parse(body);
let child = spawn('sh', [`./${payload.repository.name}.sh`]);
let buffers = [];
child.stdout.on('data', function (buffer) {
buffers.push(buffer);
})
child.stdout.on('end', function (buffer) {
let logs = Buffer.concat(buffers).toString();
console.log(logs, 'log');
console.log('开始发送邮件------------------>')
sendMail(
`
<h1>部署日期:${new Date()}</h1>
<h2>部署人:${payload.pusher.name}</h2>
<h2>部署邮箱:${payload.pusher.email}</h2>
<h2>提交信息:${payload.head_commit && payload.head_commit['message']}</h2>
<h2>部署日志:${logs.replace("\r\n", '<br/>')}</h2>
`
)
}
)
}
})
}else{
res.end('Not Found');
}
}
);
server.listen(4000, () => {
console.log('Webhook server is listening, port 4000');
}
);
把写好的三个项目 推送到github,接下来在你的服务器上 拉取三个项目,配置必要的依赖和环境 最后通过pm2去后台管理此服务
- 新建一个项目文件夹
mkdir /usr/projects
- 在服务器上生成共钥并添加github
# ssh-keygen 生成共钥的意思
# -t ed25519 指rsa算法
# -b 4096 指4096字节
# -C 指你的邮箱
ssh-keygen -t ed25519 -C "your_email@example.com"
cat /root/.ssh/id_ed25519.pub
- 安装git,并把三个项目克隆到/usr/projects下
yum install git -y
...
- 安装nvm
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
- 执行脚本
. /root/.bashrc
- 安装node稳定版本
nvm install stable
- 安装yum-utils工具包
# device-mapper-persistent-data和lvm2是储存设备映射
yum install yum-utils device-mapper-persistent-data lvm2
- 安装docker
# ce 社区版本
# 添加docker ce仓库的配置 添加Docker的yum存储库
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
# 安装containerd.io 容器运行时的RPM包
yum install https://download.docker.com/linux/fedora/30/x86_64/stable/Packages/containerd.io-1.2.6-3.3.fc30.x86_64.rpm
# 安装docker
yum install -y docker-ce
- 阿里云加速
mkdir -p /etc/docker
tee /etc/docker/daemon.json <<- 'EOF'
{
"registry-mirrors": ["https://fwvjnv59.mirror.aliyuncs.com"]
}
EOF
# 重载所有修改过的配置未文件
systemctl daemon-reload
systemctl restart docker
- 配置淘宝源
npm config set registry 'https://registry.npm.taobao.org'
- 安装 pm2
# 可以在后台启动你的服务
npm install pm2 -g
- 在webhook项目package.json配置命令
"start": "pm2 start ./webhook.js --name webhook --watch",
"stop":"pm2 stop webhook"
- 安装nginx
yum install nginx -y