Table of Contents
1. Overview
2. Early preparation
3. Overall architecture diagram
4. Environment setup
1. Environment preparation (optional)
2. Gitlab installation
3. Install Runner
4. Install the application server environment
5. Create SpringBoot project
1. Use Gitlab Spring template quickly creates a SpringBoot project;
2、添加环境变量(登录应用服务器密码)
Home Java javaTutorial Gitlab CI-CD method to automatically deploy SpringBoot projects

Gitlab CI-CD method to automatically deploy SpringBoot projects

May 11, 2023 pm 05:31 PM
gitlab springboot ci-cd

1. Overview

This article mainly records how to automatically deploy the SpringBoot project jar package through Gitlab CI/CD.

2. Early preparation

Prepare three CentOS7 servers and deploy the following services respectively:

Serial number System IP Service
1 CentOS7 192.168.56.10 Gitlab
2 CentOS7 192.168.56.11 Runner (install Docker)
3 CentOS7 192.168.56.12 SpringBoot project jar package (install jdk, maven, etc.)

The above services can also use only one CentOS7 and deploy all programs on the same machine, but it is more recommended to deploy them separately;

3. Overall architecture diagram

Gitlab CI-CD自动化部署SpringBoot项目的方法

Description:

  • Gitlab Server is used to deploy Gitlab remote warehouse. It has high CPU and memory requirements. It is recommended to have a 4-core CPU and more than 4GB of memory;

  • Runner Server is used to deploy and execute the stage defined in the .gitlab-ci.yml file; you need to have permission to access the Gitlab warehouse, you can download the code and implement it through registration (gitlab-runner register) ;

  • Your Laptop Server user deploys your application, here is the SpringBoot jar package, you need to install JDK and Maven in advance and configure the environment variables;

4. Environment setup

1. Environment preparation (optional)

Execute the following commands on three servers:

1

2

3

yum -y upgrade

yum -y install wget

yum -y install vim

Copy after login

2. Gitlab installation

Reference address:
https://about.gitlab.com/install/#centos-7
https://www.xieniao.com/article/188877.htm

(1) Install and configure necessary dependencies

1

2

3

4

5

6

7

sudo yum install -y curl policycoreutils-python openssh-server

sudo systemctl enable sshd

sudo systemctl start sshd

 

sudo firewall-cmd --permanent --add-service=http

sudo firewall-cmd --permanent --add-service=https

sudo systemctl reload firewalld

Copy after login

(2) Install mail service

1

2

3

sudo yum install postfix

sudo systemctl enable postfix

sudo systemctl start postfix

Copy after login

(3) Add gitlab mirror

1

wget https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el7/gitlab-ce-13.4.0-ce.0.el7.x86_64.rpm

Copy after login

(4) Install gitlab installation command

1

rpm -i gitlab-ce-13.4.0-ce.0.el7.x86_64.rpm --nodeps --force

Copy after login

Picture after successful installation:

Gitlab CI-CD自动化部署SpringBoot项目的方法

(5) Modify the gitlab configuration file to specify the server IP and custom port

1

vim  /etc/gitlab/gitlab.rb

Copy after login

(6) Reset and start GitLab

1

2

gitlab-ctl reconfigure

gitlab-ctl restart

Copy after login

The prompt "ok: run:" indicates successful startup

(7) Visit the GitLab page

If 502 is reported, wait for a while Try refreshing after a certain amount of time, usually about 1-2 minutes.

Gitlab CI-CD自动化部署SpringBoot项目的方法

The account set in this article: root, new password: 11112222

3. Install Runner

(1) Download one Binary file

1

sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

Copy after login

(2) Modify execution permissions

1

sudo chmod a+x /usr/local/bin/gitlab-runner

Copy after login

(3) Create GitLab CI user

1

sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

Copy after login

(4) Install and run as a service

1

2

sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner

sudo gitlab-runner start

Copy after login

If you encounter the prompt sudo: gitlab-runner: command not found, switch to the root user, you can remove sudo and execute the above command.

(5) Register Runner

Reference address: https://docs.gitlab.com/runner/register/index.html
Execute gitlab-runner register command:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

[root@localhost bin]# gitlab-runner register

Runtime platform                                    arch=amd64 os=linux pid=21527 revision=4e1f20da version=13.4.0

Running in system-mode.

 

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/):

http://192.168.56.10/

 

Please enter the gitlab-ci token for this runner:

PwF1sZPX_zsB-xChSKjH

 

Please enter the gitlab-ci description for this runner:

[localhost.localdomain]: test ci cd desc

 

Please enter the gitlab-ci tags for this runner (comma separated):

my-tag,other-tag

 

Registering runner... succeeded                     runner=PwF1sZPX

Please enter the executor: ssh, virtualbox, parallels, shell, docker-ssh, docker+machine, docker-ssh+machine, kubernetes, custom, docker:

docker

 

Please enter the default Docker image (e.g. ruby:2.6):

maven:3.3.9-jdk-8

Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded!

Copy after login

Note: The docker method is selected here, so additional docker needs to be installed on the server

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

#!/bin/bash

# 移除掉旧的版本

sudo yum remove docker \

                  docker-client \

                  docker-client-latest \

                  docker-common \

                  docker-latest \

                  docker-latest-logrotate \

                  docker-logrotate \

                  docker-selinux \

                  docker-engine-selinux \

                  docker-engine

 

# 删除所有旧的数据

sudo rm -rf /var/lib/docker

 

#  安装依赖包

sudo yum install -y yum-utils \

  device-mapper-persistent-data \

  lvm2

 

# 添加源,使用了阿里云镜像

sudo yum-config-manager \

    --add-repo \

    http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

 

# 配置缓存

sudo yum makecache fast

 

# 安装最新稳定版本的docker

sudo yum install -y docker-ce

 

# 配置镜像加速器

sudo mkdir -p /etc/docker

sudo tee /etc/docker/daemon.json <<-&#39;EOF&#39;

{

  "registry-mirrors": ["http://hub-mirror.c.163.com"]

}

EOF

 

# 启动docker引擎并设置开机启动

sudo systemctl start docker

sudo systemctl enable docker

 

# 配置当前用户对docker的执行权限

sudo groupadd docker

sudo gpasswd -a ${USER} docker

sudo systemctl restart docker

Copy after login

Register a globally shared Runner here (administrator Permissions, copy server address and Token), can be used by all projects, or you can register a separate Runner at the project level (enter the project Runner settings page, copy the address and Token).

Gitlab CI-CD自动化部署SpringBoot项目的方法

After successful registration, the registered Runner can be viewed in the Runner list

Gitlab CI-CD自动化部署SpringBoot项目的方法

Check :Run untagged jobs Indicates whether this runner can pick jobs without tags

Gitlab CI-CD自动化部署SpringBoot项目的方法

4. Install the application server environment

(1) Allow users to log in remotely (Optional)

1

2

3

4

5

6

7

vi /etc/ssh/sshd_config

修改:

PasswordAuthentication yes                     

PermitRootLogin yes

 

重启服务:

service sshd restart

Copy after login

(2) Install JDK1.8

(2) Decompress

1

2

3

tar -zxvf jdk-8u161-linux-x64.tar.gz

重命名:

mv jdk1.8.0_161 java1.8

Copy after login

(3) Configure environment variables

1

2

3

4

5

6

7

8

9

10

vi /etc/profile

 

添加以下内容:

export JAVA_HOME=/usr/local/java1.8

export PATH=$JAVA_HOME/bin:$PATH

export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar

保存退出

 

source /etc/profile

java -version

Copy after login

(3 ) Install Maven3.3.9

(2) Unzip

1

2

3

4

tar -zxvf apache-maven-3.3.9-bin.tar.gz

 

重命名:

mv apache-maven-3.3.9 maven-3.3.9

Copy after login

(3) Configure environment variables

1

2

3

4

5

6

7

8

9

vi /etc/profile

 

添加以下内容:

export MAVEN_HOME=/usr/local/maven-3.3.9

export PATH=$MAVEN_HOME/bin:$PATH

保存退出

 

source /etc/profile

mvn -v

Copy after login

5. Create SpringBoot project

1. Use Gitlab Spring template quickly creates a SpringBoot project;

Gitlab CI-CD自动化部署SpringBoot项目的方法

Gitlab CI-CD自动化部署SpringBoot项目的方法

If an error is reported, delete this line in pom.xml

If you report this error:
[FATAL] Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter- parent:pom:2.0.1.RELEASE from/to central (https://repo.maven.apache.org/maven2): Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101 .40.215] failed: Connection timed out (Connection timed out) and 'parent.relativePath' points at wrong local POM @ line 14, column 10

Modified version
1.5.9 .RELEASE

2、添加环境变量(登录应用服务器密码)

注: 其中 ssh_password 这个添加到环境变量中,取消勾选 Protect Branch (仅保护分支);修改和添加都是默认勾选,需要取消,否则,其他分支不能读取到该变量;

Gitlab CI-CD自动化部署SpringBoot项目的方法

先在应用服务器上创建一个目录,用于上传存放项目 jar 包:

1

mkdir gitlab-project

Copy after login

添加 .gitlab-ci.yml 文件时,可以先再 CI/CD Pipeline 中 的 CI Lint 中检验 .gitlab-ci.yml 文件格式

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

# 定义一些变量, 下面各阶段会使用

variables:

  server_ip: 192.168.56.12

  jar_name: demo-0.0.1-SNAPSHOT.jar

  java_path: /usr/local/java1.8/bin

  upload_path: /usr/local/gitlab-project

 

# 定义执行的各个阶段及顺序

stages:

  - build

  - upload

  - deploy

 

# 使用 maven 镜像打包项目

maven-build:

  stage: build

  image: maven:3.5.0-jdk-8

  script:

    - mvn package -B -Dmaven.test.skip=true

  cache:

    key: m2-repo

    paths:

      - .m2/repository

  artifacts:

    paths:

      - target/$jar_name

 

# 上传生成的 jar 包到你的应用服务器,这里使用 ictu/sshpass 这个镜像,是为了使用 sshpass 命令

upload-jar:

  stage: upload

  image: ictu/sshpass

  script:

    - ls -l target/

    - sshpass -p $ssh_password scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no target/$jar_name root@$server_ip:$upload_path/$jar_name

 

# 启动 SpringBoot jar包

deploy-test:

  stage: deploy

  image: ictu/sshpass

  script:

    - sshpass -p $ssh_password ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@$server_ip "nohup $java_path/java -jar $upload_path/$jar_name >/dev/null 2>&1 &"

Copy after login

这里使用了DockerHub上面的一个公共镜像(ictu/sshpass),主要是想使用启动自带的sshpass命令执行scp和ssh命令。
如果一切顺利的话,就会自动触发 CI/CD ;失败的话查看报错信息,可使用 Debug 模式执行调试命令 。

1

2

3

4

5

[root@localhost gitlab-project]# jps

22119 Jps

22073 demo-0.0.1-SNAPSHOT.jar

[root@localhost gitlab-project]# curl localhost:8080

Spring is here!

Copy after login

Gitlab CI-CD自动化部署SpringBoot项目的方法

可能遇到的问题总结:

  1. 权限问题:可以先使用 root 用户看看是不是权限问题导致,如果是的话,提升执行用户的权限;并发问题:这里没有修改 Runner 的并发数,可以修改同时可以进行的任务并发数;其他问题:读取不到配置的环境变量,取消勾选仅保护分支的选项;

  2. 未执行job:没有勾选未配置 tags 也执行选项;

The above is the detailed content of Gitlab CI-CD method to automatically deploy SpringBoot projects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How to use GitLab for project document management How to use GitLab for project document management Oct 20, 2023 am 10:40 AM

How to use GitLab for project document management 1. Background introduction In the software development process, project documents are very important information. They can not only help the development team understand the needs and design of the project, but also provide reference to the testing team and customers. In order to facilitate version control and team collaboration of project documents, we can use GitLab for project document management. GitLab is a version control system based on Git. In addition to supporting code management, it can also manage project documents. 2. GitLab environment setup First, I

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

Centos offline installation of Chinese version of GitLab Centos offline installation of Chinese version of GitLab Feb 19, 2024 am 11:36 AM

1. Download the gitlab installation package. Download the latest Chinese version of the gitlab installation package from [Tsinghua University Open Source Software Mirror Station]. The installation package comes with a simplified Chinese localization package. Download the latest gitlab installation package from [gitlab official website]. 2. Install gitlab, take gitlab-ce-14.9.4-ce.0.el7.x86_64 as an example, upload it to the centos server and use yum to install gitlabyum-yinstallgitlab-ce-14.3.2-ce.0.el7.x86_64. rpm uses yum to install gityum-yinstallgit#Install git and modify the gitlab configuration file vi

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

SpringBoot+Dubbo+Nacos development practical tutorial SpringBoot+Dubbo+Nacos development practical tutorial Aug 15, 2023 pm 04:49 PM

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.

See all articles