linux+jenkins+github+.net core CI/CD 快速部署
目标:
代码提交后,在jenkins点击build,编译通过后能让linux更新.net core 文件和重新运行
步骤:
1.腾讯云搞一台免费linux服务器:https://cloud.tencent.com/
2.服务上安装jenkins https://www.jenkins.io/doc/book/installing/linux/#red-hat-centos
3.腾讯云防火墙开放8080端口, 另一台电脑访问jenkins地址http://{公网IP}:8080/
4.jenkins获取密码Unlock解锁,安装git和github插件,msbuild,创建Pipeline 加入脚本(文章最后)
5.github设置webhook http://{公网ip}:8080/github-webhook/ application/json
6.腾讯云防火墙开放5000端口 .net core 默认5000 注意配置服务为0.0.0.0:5000 不是localhost
7.linux 新建服务
8.如何部署到其他服务器(https://blog.csdn.net/qq_32352777/article/details/109267748)
7.1 sudo nano /etc/systemd/system/{service}.service 7.2 加入以下配置 [Unit] Description={project} .NET Core 6.0 Web API After=network.target [Service] WorkingDirectory=/opt/{project} ExecStart=/usr/share/dotnet/dotnet /opt/{project}/{project}.dll Restart=always RestartSec=10 SyslogIdentifier={project} User={你的linux用户名} Environment=ASPNETCORE_ENVIRONMENT=Production Environment=ASPNETCORE_URLS=http://0.0.0.0:5000 # 添加这一行 [Install] WantedBy=multi-user.target 7.3 sudo systemctl daemon-reload sudo systemctl enable roadtodreams sudo systemctl restart roadtodreams sudo systemctl status roadtodreams
Pipeline脚本:
pipeline { agent any environment { DEPLOY_PATH = '/opt/{project}' // 设置部署路径 DOTNET_ROOT = '/usr/share/dotnet' PATH = "/usr/share/dotnet:$PATH" TARGET_FRAMEWORK = 'net6.0' // 指定目标框架 PROJECT_PATH = '{project}/{csproj}.csproj' // 替换为你的项目路径 } stages { stage('Checkout') { steps { // 检出代码 git branch: 'main', url: 'https://github.com/{name}/{project}.git' } } stage('Build') { steps { script { // 恢复依赖项 sh "dotnet restore ${PROJECT_PATH}" // 构建项目 sh "dotnet build ${PROJECT_PATH} --configuration Release" // 发布项目,指定目标框架 sh "dotnet publish ${PROJECT_PATH} --configuration Release --framework ${TARGET_FRAMEWORK} --output ./publish" } } } stage('Deploy') { steps { script { // 确保部署目录存在 sh "sudo mkdir -p ${DEPLOY_PATH}" // 将发布文件复制到部署路径 sh "sudo cp -r ./publish/* ${DEPLOY_PATH}" } } } stage('Run') { steps { script { // 停止正在运行的实例(假设使用的是 systemd 服务) sh "sudo systemctl stop {service}" // 启动新实例 sh "sudo systemctl start {service}" // 你可以添加检查服务状态的命令 sh "sudo systemctl status {service}" } } } } }