CentOS + Jenkins + nginx + gitlab front end automation deployment full record

centos jenkins nginx gitlab end


0. Preface

When we were developing a new project , You always need to deploy the front end to the test server , Give test or product access . In a nutshell , If you want to deploy the front end to the server , The server needs to provide a service to access the front end . If we don't involve in development Node.js, Then we need the server to provide a service to access the front end , May be IIS service ,Nginx Service or Tomcat service , Wherever deployed , When the current side code is updated frequently ( Especially in the development stage ), We need to keep packaging to replace the code on the server . Maybe the O & M will help us replace , Or we can do it ourselves ftp Replace in a way . All in all , This way, it's more complicated .

Front end automated deployment , We may also often hear , adopt Jenkins and gitlab Get through to the warehouse , When our warehouse code specifies the branch push after , Will automatically trigger Jenkins The task of . adopt Jenkins Mission , We can automatically update the latest front-end code , And automatically package the code on the server through scripts , And update the Nginx In the specified directory , And restart Nginx service . To achieve the purpose of front-end automatic deployment .

Next , It's a game from 0 To 1 The whole process of front-end automated deployment , The period is also a pit step by step , recorded , For your reference , learn from each other . There may be some imperfections or mistakes , You are also welcome to correct .

My development system is windows, The test server is centos ,Mac There may be different tools or operations on the system , The code warehouse is placed in gitlab in , For example GitHub perhaps Code cloud Such as platform , Some configurations are also different , Please judge for yourself .

The target group of this article : Preliminary and intermediate front-end development

  1. Terminal tools
  • I am a Windows development environment , So I chose MobaXterm As an operation centos Terminal , at present windows There are also many terminal tools in , such as SecureCRT、Xshell、Putty etc. , Some need to pay , Depending on your hobby
  • MobaXterm Optional free version

img

  1. Linux centOs A server

  2. gitlab Deposit vue Project warehouse

2. Installation environment

install Java Environmental Science

Jenkins It's open source. , Use Java Continuous integration tools written by , Therefore, you need to install... Before installation Java

  1. Check if the system is installed java Environmental Science
java -version
 Copy code 

findjava.png

If you can find , Then skip the installation Java This step 2. install Java

yum install java
 Copy code 

install Jenkins

1. Download dependency
 Copy code 
sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
 Copy code 
2. Import secret key
 Copy code 
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
 Copy code 
3. install
 Copy code 
yum install jenkins
 Copy code 

image-20210814155507870.png

Installation completed ,Jenkins Default port for 8080

If the port conflicts , You can modify the port

vim /etc/sysconfig/jenkins
 Copy code 

find JENKINS_PORT="8080" modify

image-20210814162636090.png

vim Modify port simple command :

  • adopt ↑↓ Move the cursor to the line to be modified

  • Press i Enter edit mode

  • After modification, press Esc Exit edit mode

  • Press :wq Save and exit

  • After repair

3. To configure Jenkins

start-up Jenkins

service jenkins start
 Copy code 

restart / Stop Jenkins The order will start in restart|stop that will do

Check the status

systemctl status jenkins
 Copy code 

appear active running It means success

image-20210814165822990.png

Access address

http://[centos Service address ]:[Jenkins port , Default 8080]
 Copy code 

image-20210814170239720.png

Get... On the terminal Jenkins password

cat /var/lib/jenkins/secrets/initialAdminPassword
 Copy code 

Get the password Fill in the page above -> continue

plugin.png

Select the recommended plug-in for the next step

install.png

After installation , Create administrator user

user.png

image-20210814171550469.png

thus ,Jenkins Installed

Installing a plug-in

Manage Jenkins -> Manage Plgins

manage.png

install Generic Webhook Trigger plug-in unit Realization Jenkins+WebHooks Continuous integration

image-20210816083600244.png

After installation, you need to Restart Jenkins service

Create tasks

1. Create tasks

image-20210816104107464.png

  1. Enter task name

crate-job.png

3. To configure git

git.png

This error is due to our centos Is not installed on the system git

install git

stay centos Install... Through commands in the system git

yum install -y git
 Copy code 

Installation completed Check whether the version verification is installed successfully

git version
 Copy code 

To configure git Authentication

installed git after It still reports an error Prompt authentication failed

image-20210816130622141.png

You want to configure git User information for [ Yours git user name , password ]

image-20210816132227483.png

Appoint git Branch ( When the branch has push In operation , Will trigger the current Jenkins Mission )

image-20210816141609593.png

Configure build triggers

We were just Jenkins Installed in Generic Webhook Trigger plug-in unit

We select... In the build trigger Generic Webhook Trigger Options , take Jenkins and gitlab coordinate

image-20210816143402614.png

Jenkins Set up API Token

Manage Jenkins --> Manage Users--> Select the user --> Set up --> newly added Token

image-20210816143838276.png

Copy the generated token

image-20210816143915634.png

To configure gitlab hook

Sign in gitlab Enter the project you want to deploy >settings>Integrations>add webhook

image-20210816144621506.png

After preservation You can test whether the configuration is effective

image-20210816150044227.png

choice Test->Push envents If you are prompted successfully Indicates that the configuration is normal

At this time Jenkins A build record will also be added to the task

image-20210816150252336.png

install Node

We are git After pulling the code, you need to pass npm install To install the package So before this configuration We still need to centos Installation on system Node

perform

yum install -y node
 Copy code 

Jenkins The build

So far, , When we push After code ,Jenkins The latest code will be automatically pull To centos in , Next we need to execute... In the code npm install Installation depends on , Then the project will be npm build pack

stay Jenkins Configuration in progress , Add build steps

image-20210816163547804.png

choose Execute shell adopt shell Command to operate

Execute the following script in the command box

echo ' Build version number :'${BUILD_NUMBER}
 # Every time you update the code, you need to install the dependent package prevent package.json to update 
npm install
# build command 
npm run build
echo ' Build complete '
 Copy code 

And then after saving We push Code Check it out

image-20210816170530902.png

After the task is successfully built There are more in the workspace node_modules dist Folder It shows that our steps are successful

We are centos Of /var/lib/jenkins/workspace/ You can find us from git On clone Code for

Remember this path

/var/lib/jenkins/workspace/

install Nginx

At present, the code has been pushed to centos in , Now we need to start a Nginx Service to access the front-end page Detailed steps view here

Install compilation tools and library files

gcc yes linux The compiler under , It can be compiled C,C++,Ada,Object C and Java Other languages

yum -y install gcc
 Copy code 

install PCRE

pcre It's a perl library , Include perl Compatible regular expression library ,nginx Of http Module USES pcre To parse regular expressions , So you need to install pcre library

yum install -y pcre pcre-devel
 Copy code 

zlib install

zlib The library provides many ways to compress and decompress nginx Use zlib Yes http The contents of the package go on gzip, So you need to install

yum install -y zlib zlib-devel
 Copy code 

install openssl

openssl yes web The cornerstone of secure communication , No, openssl, It can be said that all our information is streaking

yum install -y openssl openssl-devel
 Copy code 

install Nginx

1. Download a stable version of Nginx

wget http://nginx.org/download/nginx-1.20.1.tar.gz
 Copy code 

2. Decompress the package to usr/local/src

tar -zxvf nginx-1.20.1.tar.gz
 Copy code 

3. Compilation and installation

cd /nginx-1.20.1
./configure
make
make install
 Copy code 

4. start-up Nginx

Find the installation path

whereis nginx
 Copy code 

image-20210816193128043.png

frequently-used Nginx command :

# start-up 、 stop it nginx
cd /usr/local/nginx/sbin/
./nginx # start-up
./nginx -s stop # stop it , Direct search nginx process id Reuse kill Order to force the killing process
./nginx -s quit # Exit stop , wait for nginx The process stops after processing the task
./nginx -s reload # Reload the configuration file , modify nginx.conf Use this command after , The new configuration will take effect
 Copy code 

start-up Nginx Default port 80 If the port conflicts, you can modify the port ( Specific modification methods , I'll say later )

Visit the page to view Nginx Whether it starts normally

image-20210816193902728.png

indicate Nginx Start up normal

5. Front end build After the file is synchronized to Nginx In service

at present ,centos On Nginx The service has , front end build The code after has , Now you need to synchronize the front-end code to Nginx In service , So that we can go through Nginx Service access

Sort out what we're going to do next :

  • stay Nginx in html Create under folder teacher file , Put the packaged code of the front end here
  • To configure Nginx conf file Configure ports and access paths
  • Scripting will Jenkins in workspace Front end code under Package and copy to nginx/html/teacher in
  • restart Nginx service

Nginx Created in teacher Folder

centos Find Nginx In the folder

If you forget, you can pass

# lookup nginx The position of 
whereis nginx
 Copy code 

We will be in html Create under folder teacher( Name at will ) To store the front-end code

cd /usr/local/nginx
# create a file 
mkdir teacher
 Copy code 

To configure Nginx conf file

Next, we need to configure the proxy service for our front-end code To visit

vim /usr/local/nginx/conf/nginx.conf
server {
listen 9091;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html/teacher;
index index.html;
}
}
 Copy code 

The following configuration

image-20210817191517497.png

Write a script

The next thing to do is Write a script When Jenkins After pulling the code You need to execute npm install Install all dependencies

Then do it again npm run build Yes Vue Package the project

Will pack up the dist The folder is typed tar Put the bag in nginx/html/teacher Under the folder And extract the Delete tar package

Writing scripts requires some basic knowledge shell command , Specific tutorials can be searched by yourself , To learn

For convenience Jenkins Execute the script , We are in the front-end code build Folder (Vue project ) Create a deploy.sh Script

So if you modify the script No more changes Jenkins Build script for direct push Code can be updated

The specific script content is as follows :

deploy.sh

#!/bin/bash
# Once the return value is non-zero , The entire script will exit immediately 
set -e
# Script directory 
sh_dir=$(cd "$(dirname "$0")";pwd)
# Project root 
base_dir="${sh_dir}/.."
# dist Catalog 
dist_dir="${base_dir}/dist"
# nginx Catalog 
nginx_dir="/usr/local/nginx"
# teacher Catalog 
teacher_dir="${nginx_dir}/html/teacher"
# sbin Catalog 
sbin_dir="${nginx_dir}/sbin"
# Package name 
tar_name="teacher.tar.gz"
echo '==================== Begin to build ==========================='
echo ' Build version number :'${BUILD_NUMBER}
echo ' Current directory : ' ${base_dir}
# Return to the following directory Installation package 
cd ${dist_dir}
npm install
# Delete the old dist file 
rm -rf dist
npm run build:prod
# take dist The catalog is packaged into nginx/html/teacher Under the table of contents 
cd ${dist_dir}
tar -zcvf "${teacher_dir}/${tar_name}" *
echo '==================== Pack up ==========================='
# go back to Nginx Unzip the package just hit under the directory 
cd ${teacher_dir}
tar -zxvf ${tar_name}
# Delete gz package 
rm -rf ${tar_name}
echo '==================== Code update complete ========================'
# restart Nginx
cd ${sbin_dir}
./nginx -s reload
echo '==================== Restart complete ========================'
 Copy code 

The whole script has been written , So how to make Jenkins Pull the latest code to execute

open Jenkins--> Find the task we created --> To configure --> Update build -> modify Execute shell Save the script in :

image-20210817192709069.png

# The current location is in the root directory of the code warehouse 
cd build
// Get into build Folder Execute the script
sh deploy.sh
 Copy code 

restart Nginx service

We just modified Nginx The configuration has not yet taken effect , Then go back to centos in

restart Nginx service

Specific commands :

cd /usr/local/nginx/sbin
# restart Nginx service 
./nginx -s reload
 Copy code 

After the restart ,commit push The script just added in the front-end code

push after Jenkins automatically Build Our automated deployment mission

Jenkins Permission problems

Everything seems to be all right , When we push Code When you build a task, you find Jenkins Package task error , as follows :

image-20210817115812107.png

There is a permission problem , So in centos In the system , Direct manual execution deploy.sh Test the script , Was a success , There is no permission problem . The problem is Jenkins On , So we installed Jenkins When , To the user is jenkins, This user certainly does not have root jurisdiction .

The solution is to modify Jenkins Users of

modify /etc/sysconfig/jenkins file

image-20210817115916934.png

vim /etc/sysconfig/jenkins
JENKINS_USER="root" # Change to root
 Copy code 

image-20210817120215510.png

cd /var/lib
chown -R root:root jenkins
# restart jenkins service 
service jenkins restart
 Copy code 

After the modification , Again push Code test , Finally, the deployment is successful , The page can be accessed normally , The code is up to date . thus , Our entire front-end automation deployment is almost perfect .

Up to now , The whole front-end automated deployment process has been completed


however ..

Jenkins It takes up a lot of memory

When you think everything is all right , The back-end found that the server compares cards , Check the memory usage , Find out Jenkins High occupancy

centos perform top command Check the memory occupied by the current program :

# lookup java service 
jps
# top The command is the of the monitoring system cpu Memory usage 
top -d 2 -c -p [ Just found Jenkins ID]
 Copy code 

The picture below is Jenkins The operation of the task :

image-20210817184501218.png

Next, solve Jenkins The problem of high memory consumption ,

Modify the configuration file :

vim /etc/sysconfig/jenkins
 Copy code 

take JENKINS_JAVA_OPTIONS Make the following changes :

# JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true"
JENKINS_JAVA_OPTIONS="-XX:MaxPermSize=512m -Djava.awt.headless=true"
 Copy code 

image-20210817184652723.png

After revising :wq after restart Jenkins service

service jenkins restart
 Copy code 

ending

Through the above one-way operation , The automatic deployment of the front end is completed . There's a lot of room for optimization , such as Jenkins Services and the code to deploy the front-end Nginx Not on the same machine , Need to remotely transfer files and execute shell command . For example, after the successful construction Jenkins You can send notification email to test related personnel, etc . If we have a chance to share these next time .

There are still many imperfections in the whole process , Focus on experiencing this process , I hope you are not limited to the front-end code , It can be done to jenkins Nginx shell Script vim command And others around the front-end also have some understanding , It's more difficult to improve our competitiveness .

We also welcome your comments , Learn from each other and make progress .

The original text of this article is sent to the front-end interview question collection of another account of our team centos+jenkins+nginx+gitlab Full record of front-end automated deployment , You are also welcome to pay attention to .

Recently, our team's small partners also developed a small , cheng , order , Let me see the code in the front-end interview questions , Included 600 Multiple front-end interview questions , I hope I can help my friends on the way to the interview . You can also visit WX Search directly in Front end interview question collection Focus on .

Reference material

More complete front-end interview questions

Jenkins+Nginx+Github/Gitlab Automate building and deploying front-end projects

centOS7 install nginx And nginx To configure

CentOS Next tar Package decompression details ( Unzip to the specified folder )

vue/react The automation deployment scheme that cannot be ignored in the project

版权声明
本文为[Renren loan big front-end technology center]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909142454899R.html

  1. Contrôle de l'arbre en vue converti en style de table
  2. CSS3 animation flash Effect
  3. Discuter des propriétés de la file d'attente pour l'événement bloc
  4. Node around USModules
  5. Webpack - - Premier aperçu (concept de base)
  6. Mise en œuvre du cadre de base mvvm par JS natif
  7. Calculer les propriétés par rapport aux auditeurs, etc.
  8. Configuration standard dockerfile et docker-composer.yml
  9. Collection de questions d'entrevue HTML
  10. Conteneur, définir la largeur et la hauteur ne répond pas?
  11. Introduction et syntaxe des objets (mise à jour à long terme)
  12. Bubble Mart invests in cat galaxy, which is a vertical e-commerce platform around the quadratic element
  13. Exigences et dépendances dans package-lock.json
  14. Mouvement tridimensionnel de la terre, du ciel et de la lune basé sur three.js
  15. Compréhension et analyse de l'objet de base JS
  16. Simple use of status data management (context, mobx, Redux)
  17. Simulated drumming
  18. Array method
  19. Performance optimization issue 03 - HTTP request optimization
  20. Vue learning -- watch listener
  21. Learn more about nexttick in Vue
  22. Talk about some moves used by vue3.0 in the project - External skill chapter (I)
  23. JavaScript genrator generator
  24. La dernière réponse à l'entrevue de développement Android, l'hiver froid de l'industrie
  25. Maserati's motorcycle has less than 10 in the world. It is definitely a work of art
  26. 2021 partage des questions du dernier examen écrit d'entrevue Android, pas d'accord
  27. Programmation asynchrone Java scirp, développement frontal de base
  28. 2021 dernier examen écrit d'entrevue Android, écrit trop bien
  29. Quels aspects doivent être pris en considération dans le tableau principal du distributeur libre - service?
  30. He inherited his mother's hundreds of millions of property for his boyfriend to squander. Unexpectedly, he was ruthlessly abandoned when he had 100 yuan left
  31. The fuel cost is half less than that of fuel vehicles at the same level. Is it really cheap to use song Pro DM?
  32. Le dernier résumé de l'expérience d'entrevue d'embauche de l'école Android de l'usine est nécessaire pour l'usine
  33. Le dernier dictionnaire avancé de programmeurs d'usine, l'expérience d'entrevue d'embauche de l'Agence de développement Android
  34. La dernière collection d'entrevues Android Golden nine Silver ten
  35. L'expérience d'entrevue de l'Ingénieur d'algorithme de saut d'octets, 2 mois d'entrevue Tencent, station B, Netease et ainsi de suite sur 11 entreprises résumé!
  36. La dernière collection d'entrevues d'Android Golden nine Silver ten recommande un projet github
  37. Yuan Li's recent situation revealed that he was obsessed with public welfare, dressed simply and fearless, grew fat, and married an 11-year-old husband
  38. Initial experience of template tool plop of [front end Engineering]
  39. Dernière question d'entrevue avancée et réponse d'Alibaba Android, Alibaba P8 vous apprendra en personne
  40. Partage des dernières questions d'entrevue pour Android haute fréquence, Introduction aux compétences d'entrevue pour le développement d'Android
  41. Partager les dernières questions d'entrevue Android haute fréquence avec quelques conseils
  42. About JavaScript modules
  43. Iteratable object and class arrays
  44. Function realization of Vue elementui exporting excel form
  45. Use canvas to realize a small screenshot function
  46. Object oriented programming (2)
  47. Several common value transfer methods between Vue components
  48. Démarrer avec le serveur de base zéro: Hello World
  49. J'a I construit un escalier pour aller sur la lune, combien de façons puis - je poursuivre la sœur Chang'e?
  50. CSS implémente la fonction d'expansion et d'arrimage du Texte multiligne
  51. Varlet CLI | vue3 Component Library Quick Prototyping Tool
  52. Belle vue sur les trois rivières Xiapu
  53. La partie Web qui déploie SharePoint ajoute son propre module de fonctionnalité
  54. React Native (mise à jour à long terme)
  55. La conception et le codage de l'arbre binaire requis pour chaque entrevue d'embauche de la société Java millet;
  56. 10 jours pour obtenir l'offre d'emploi Android d'Alibaba, entrevue Android
  57. A remporté avec succès Byte, Tencent, Pulse offer, 7 ans Java une expérience d'entrevue de baise,
  58. 10大前端常用算法,web应用与开发
  59. Nginx - minimum configuration! You deserve it
  60. Les questions d'entrevue couramment utilisées pour le cadre Java sont - elles prometteuses pour le développement Java?