Server as a part of development, and now a lot of commercial companies deployed in the production environment on the server is CentOS system! Let us understand understand also in reasonable!
As front-end developers, we need to get out of our comfort zone. Expand their technical breadth and depth, only like this! So we can “make it bigger and stronger.”
The purpose of this article is to introduce some common environment configuration tips on Centos, so that front-end folks can take the next step on the road to Centos!
Centos
Centos is a free, open source Operating system based on Linux. The following are some common operations
#Copy files locally to a remote serverSCP output. TXT [email protected]: / data /Copy the code
output.txt
: Local fileroot
: Account used to log in to the remote server47.93.242.155
: IP address of the remote server/data/
: Directory of the remote server
#Copy all files in the HTTPS directory on drive D to the remote /data directorySCP D/HTTPS: / * [email protected]: / dataCopy the code
Link to the remote Centos server locally
SSH -p Port Username @Server IP address
Example:
SSH -p 22 at [email protected]
#Enter the login password
#successful
Copy the code
Yum switch to Alibaba source
cd /etc/yum.repos.d/
curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repo
#Regenerate the cache -- check the result, if there is aliyun, it is successful
yum makecache
Copy the code
other
#Create/data /testdirectory
mkdir /data/test
#Create the /data/newtest directory
mkdir /data/newtest
#Create/data /test/ index. The HTML file
touch /data/test/index.html
#Edit the file
vi /data/test/index.html
#Viewing file Contents
cat /data/www/index.html
#Will `testCopy all files in 'newtest' directory to 'newtest' directoryCp - r/data/test / * / data/newtest
#Delete the /data/newtest/index.html file
rm -rf /data/newtest/index.html
#Will `testMove all files in the 'directory' to the new directory 'newtest'
mv /data/test/* /data/newtest
Copy the code
#View the path of the current directory
pwd
Copy the code
#Check which process occupies the portNetstat LNP | grep 88 # 88, please change to port, you need such as: 80Copy the code
Perform netstat LNP | grep port after prints out occupied process and its number
#Kill the process whose id is 1777 (please enter according to actual situation)
kill -9 1777
Copy the code
View the distribution information about the current Centos operating system
cat /etc/redhat-release
Copy the code
The Nginx server is set up
Nginx is a high performance HTTP and reverse proxy Web server, using Nginx website: Baidu, JD.com, Sina, netease, Tencent, Taobao… .
The Nginx server is installed on Centos
Here we use yum to install the Nginx server.
yum install -y nginx
Copy the code
Start the Nginx server
The Nginx server is not started. Start the Nginx server first.
nginx
Copy the code
At this point, visit http://< your domain name or IP> to see the Nginx test page
If no, try the nginx -s reload command to restart nginx
The static server access path was configured
The Web service for Internet users to access the server is provided by Nginx. Nginx needs to configure the path information of static resources to correctly access the static resources on the server through the URL.
Open the default Nginx configuration file /etc/nginx/nginx.conf and modify the Nginx configuration
vi /etc/nginx/nginx.conf
Copy the code
Will default to /usr/share/nginx/html; /data/ WWW; That is as follows:
Example code: /etc/nginx/nginx.conf
user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 80 default_server; listen [::]:80 default_server; server_name _; Root /data/ WWW; include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } }Copy the code
The configuration file uses /data/ WWW /static as the root path for all static resource requests, such as access: /data/ WWW /static/ index.html /data/ WWW /static/ Now we need to restart Nginx for the new configuration to take effect, such as:
nginx -s reload
Copy the code
Create the first static file
Now let’s create a new static file and see if the service works.
First let’s create a WWW directory in /data directory, such as:
mkdir -p /data/www
Copy the code
Create our first static file index.html in the /data/ WWW directory
touch /data/www/index.html
vi /data/www/index.html
Copy the code
Example code: /data/ WWW /index.html
<! DOCTYPEhtml>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>The first static file</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
Copy the code
Now visit http://< your domain name or IP>/index.html and you should see the page output Hello World!
At this point, a static server based on Nginx is set up, and all static resources in /data/ WWW can be accessed directly by domain name /IP.
If no information is displayed, refresh the browser page
Nginx Configures the SSL generic domain name certificate
Here is the use of Ali Cloud free certificate, the term for one year
Log in to the SSL Certificate console to download the certificate
Download the SSL certificate package to a local directory and decompress it to a desired directory, for example, D:/ HTTPS /. The pem and key files are used here. The name of the file can be changed.
Create the /data/cert directory in the connection server window to store the certificate files
mkdir /data/cert
Copy the code
Upload the file to the remote server using the SCP command (you need to open a new terminal here, do not use the server connection window):
SCP D/HTTPS: / * [email protected]: / data/certCopy the code
Copy all files in D:/ HTTPS/to the /data/cert directory on the remote server
D:/https/
: Indicates the absolute path of the local fileroot
: Log in to the remote server as user root47.93.242.155
: IP address of the remote server/data/cert
: Specifies the path on the remote server
Enable 443 listening
Nginx only listens to port 80 by default.
Here we have the listener on port 443 on as well.
Edit the global configuration file
vi /etc/nginx/nginx.conf
Copy the code
Example code: /etc/nginx/nginx.conf. The descriptions are in the comments
# For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80; # Change domain name server_name nsuedu.cn; Rewrite ^(.*) https://$host$1 permanent; } # Settings for a TLS enabled server. server {# SSL listen 443 SSL http2 default_server; listen [::]:443 ssl http2 default_server; Enter your domain name server_name nsuedu.cn; # alter static file path root /data/ WWW; Ssl_certificate "/data/cert/4726867_www.nsuedu.cn.pem"; Ssl_certificate_key "/data/cert/4726867_www.nsuedu.cn.key"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; Ssl_ciphers HIGH:! aNULL:! MD5; Ssl_prefer_server_ciphers on; Load configuration files for the default server block.include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } }Copy the code
Restart the nginx
nginx -s reload
Copy the code
Go to http://nsuedu.cn/ in your browser
Configure the Nginx reverse proxy
The client is unaware of the proxy server and does not need to perform any configuration on the client. The user only requests the reverse proxy server. The reverse proxy server selects the target server and returns data to the client.
The reverse proxy server and the target server are the same server externally. The IP address of the proxy server is exposed, but the IP address of the real server is hidden.
Reference from principle to actual combat, thoroughly understand Nginx!
Access path :/ API /getUser
- When the nginx configuration file
proxy_pass
็ The url at the end of the belt/
when:
server { listen 80; server_name www.123.com; Location/API / {proxy_pass http://127.0.0.1:18081/; }}Copy the code
Agent to the backend path is: http://127.0.0.1:18081/getUser, omitted to match/API/path;
- When the nginx configuration file
proxy_pass
็ Not at the end of the URL/
when:
server { listen 80; server_name www.123.com; Location/API / {proxy_pass http://127.0.0.1:18081; }}Copy the code
Agent to the backend path is: http://127.0.0.1:18081/api/getUser, along with the match to/API/path, reverse proxy together;
Set up the Node.js environment under Centos
Node.js is JavaScript that runs on the server and is built on the Chrome JavaScript V8 engine.
There are several ways to install Node.js
- Method one: From
EPEL repository
The installationNode.js
—yum install nodejs
.insufficientInstallation:node/npm
If the version is earlier, you need to manually switch the version - Method two: use the official compiled binary data package to install, insufficient: the installation steps are complicated
- Method 3: Pass
NVM
Installation is convenient and quickinsufficient: The foreign network is not good when installing ๐ฅถ - Method four: the source code is downloaded after compilation and installation, the version is the latest
Yum install nodejs
Check the nodeJS version of the current system
sudo dnf module list nodejs
Copy the code
You can see that there are three versions of Node:10,12, and 14. There is a [D] symbol on version 10, which represents the version the system will install by default. If you want to switch to the default installed version, execute the following command
sudo dnf module enable nodejs:14
Copy the code
Install the Node
sudo dnf install nodejs
Copy the code
Check the node version. The node version is Node14
node --v
Copy the code
Install in NVM mode
We may be working on two projects at the same time with different versions of Node. Maintaining multiple versions of Node can be very difficult, and NVM is designed to solve this problem. It is easy to switch between multiple versions of Node on the same device
Note: If you use NPM /yarn in the following Jenkins script, the command cannot be found. I don’t know how to solve this problem
The following is the latest stable version (202/04) : you can go to the NVM website to have a look and replace it with the latest link
The curl - o - https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | cpCopy the code
You also need to run the following command to confirm the changes from the previous command
source ~/.bash_profile
Copy the code
View the Node version list
nvm list-remote
Copy the code
Install a long-supported version
NVM install 14.16.1Copy the code
Check whether the installation is successful
nvm current
node -v
npm -v
Copy the code
Use the echo $PATH environment variable to view the installation location
echo $PATH
#Print out the results, need to take out the ` / root/NVM/versions/node/v14.16.1 / bin `
Copy the code
Install using an officially compiled binary package
Note: In this mode, the Jenkins script running on NPM /yarn works properly
Here’s the latest stable release (201/04) : go to the node.js website and replace it with the latest link
Download 14.16.0 to /data
CD/data wget HTTP: / / https://nodejs.org/dist/v14.16.0/node-v14.16.0-linux-x64.tar.xzCopy the code
When the download is complete, unzip it
The tar xvJf node - v14.16.0 - Linux - x64. Tar. XzCopy the code
Move the decompressed node.js directory to the /usr/local directory
Node - mv v14.16.0 - Linux - x64 / usr/local/node - v14Copy the code
Configure the node soft link to /bin directory
ln -s /usr/local/node-v14/bin/node /bin/node
Copy the code
Configure and use NPM
NPM is the package management and distribution tool for Node.js. It makes it easier for Node.js developers to share code and snippets
NPM is already included in the node download package, we just need to soft link it to the bin directory
ln -s /usr/local/node-v14/bin/npm /bin/npm
Copy the code
Configuring Environment Variables
Adding the /usr/local/nod-v14/bin directory to the $PATH environment variable makes it easy to use third-party tools installed globally through NPM
echo 'export PATH=/usr/local/node-v14/bin:$PATH' >> /etc/profile
Copy the code
Make the environment variable effective
source /etc/profile
Copy the code
The use of NPM
Configure taobao source through NPM
npm config set registry https://registry.npm.taobao.org
npm get registry
Copy the code
Install YARN globally and configure Taobao source
npm install yarn -g
yarn config set registry http://registry.npm.taobao.org/
yarn config get registry
Copy the code
Install Docker on Centos
Docker is an open source application container engine that allows developers to package their applications and dependencies into a portable image that can then be published on any popular Linux or Windows machine
The difference between Docker and virtual machine
-
Docker is a container based on the Linux kernel
-
Docker is smaller: containers run incomplete operating systems (although they can), and virtual machines must run full operating systems
-
Docker starts faster: a virtual machine takes a few minutes to start, while a Docker container can start in milliseconds
-
Use/function
- The virtual machine is better at completely isolating the entire running environment. For example, cloud service providers often use virtual machine technology to isolate different users.
- Docker is usually used to isolate different applications, such as front end, back end, and database.
-
metaphor
- Docker is like a container: the packaging of various goods (packaging various applications and their dependent runtime environments into standard containers, separated from each other)
- Server virtualization is set up as if on the dock (physical host and virtualization layer)Multiple independent “quays” – warehouses (virtual machines)
- Have completely independent (isolated) space;
- Belonging to a different customer (virtual machine owner);
- Each repository has its own repository manager (the operating system kernel of the current virtual machine) and cannot manage other repositories. There is no information sharing
Install and configure Docker
Before the installation, you need to install the device-mapper-persistent-data and LVM2 dependencies.
device-mapper-persistent-data
ๆฏLinux
The next storage driver,Linux
Advanced storage technology on.Lvm
Is used to create logical disk partitions. Here we useCentOS
็Yum
Package manager installs two dependencies:
yum install -y yum-utils device-mapper-persistent-data lvm2
Copy the code
After the dependency installation is completed, we add aliyun’s Docker image source into it. Can speed up Docker installation.
sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
Copy the code
yum install docker-ce -y
Copy the code
Once installed, we can start Docker using systemCTL startup. Systemctl is the Linux process management service command that helps us start Docker
systemctl start docker
systemctl enable docker
Copy the code
Next, run docker -v. This command can be used to view the version information of the docker installation. Of course, it can also help us check the docker installation status. If the version information is displayed normally, Docker has been successfully installed.
docker -v
Copy the code
Setting startup
chkconfig docker on
Copy the code
other
Display all containers
docker ps
Copy the code
The local mirror list is displayed
docker images
Copy the code
Example Delete one or more local images
docker rmi imageID
Copy the code
Start/close/restart the container
docker stop containerID
docker start containerID
docker restart containerID
Copy the code
Delete one or more containers
docker rm containerID
Copy the code
Configure the Aliyun image source
After the installation of Docker is completed, when we go to pull Docker image, we generally go to the official Docker source to pull image by default. But the domestic Internet speed is too slow, so choose us to replace ali Cloud image warehouse source image download speed.
Log in aliyun official website, open aliyun container image service. Click the image accelerator at the bottom of the left menu and select CentOS (as shown below). To change the source address of the Docker image, run the command as prompted on the official website.
Configuring Nginx in Docker (recommended)
Refer to the Nginx container tutorial
docker container run -d -p 4030:80 --rm --name mynginx nginx
Copy the code
The meanings of the parameters in the preceding command are as follows.
-d
: Runs in the background-p
: Map port 80 of the container to 127.0.0.1:4030--rm
: After the container stops running, the container files are automatically deleted--name
: The container name is mynginx- At the end of the
nginx
: indicates that the container is run against the Nginx image.
If there are no errors, you can open your browser and access IP:4030. Normally, the welcome page for Nginx is displayed.
Then, the container is terminated and the container file is automatically deleted due to the –rm parameter.
docker container stop mynginx
Copy the code
Configure Nginx in Docker mode 2
Download an official Nginx image locally
docker pull nginx
Copy the code
The downloaded image will appear in the list of images
docker images
Copy the code
Run the container
docker run --name=nginx -d -p 4030:80 nginx
Copy the code
The explanation of the above command is as follows:
--name
: Sets the name of the container;-d
: indicates running the container in the background.-p
: Specifies the port mapping.4030
Is the host port,80
Is the port inside the Nginx container;- At the end of the
nginx
: indicates that the container is run against the Nginx image.
As is shown in
Then in the browser to http://47.93.242.155:4030/
Configure a reverse proxy for Nginx in Docker
To modify the Nginx configuration file, first go into the Nginx container and use the following command to go into the container
docker exec -it nginx /bin/bash
Copy the code
Explanation of the above command:
-it
: indicates that a pseudo terminal is assigned.nginx
: indicates the name of the container. You can also use the container ID here./bin/bash
: performs bash operations on the container.
We used ls to look at the file structure and found that it was actually a Linux operating system.
Take another look at the operating system distribution details
cat /etc/issue
Copy the code
It is a Debian system
Debian
system
By the way, some basic operations of the Debian system are introduced
#First it needs to be updated
apt-get update
#Install vim
apt-get install vim
Copy the code
Change the image to Tsinghua Source
See the Debian Image Use Help
If an HTTPS source cannot be pulled, use the HTTP source first and install:
sudo apt install apt-transport-https ca-certificates
Copy the code
View the Debian version so that you can select the corresponding image source
Debian Version Introduction:
- The official next generation Debian distribution will be codenamed as
buster
- Debian 9 (
stretch
) — The stable version that was eliminated - Debian 8 (
jessie
) — The stable version that was eliminated - Debian 7 (
wheezy
) — The stable version that was eliminated - Debian 6.0 (
squeeze
) — The stable version that was eliminated - Debian GNU/Linux 5.0 (
lenny
) — The stable version that was eliminated - Debian GNU/Linux 4.0 (
etch
) — The stable version that was eliminated - Debian GNU/Linux 3.1 (
sarge
) — The stable version that was eliminated - Debian GNU/Linux 3.0 (
woody
) — The stable version that was eliminated - Debian GNU/Linux 2.2 (
potato
) — The stable version that was eliminated - Debian GNU/Linux 2.1 (
slink
) — The stable version that was eliminated - Debian GNU/Linux 2.0 (
hamm
) — The stable version that was eliminated
View version Information about the current operating system release. This command makes it clear whether it is RedHat or another distribution, and the specific version number, such as 3.4 or 5.4, etc
cat /etc/os-release
Copy the code
Modifying an Image File
vi /etc/apt/sources.list
Copy the code
The modification is as follows:
#Source images are annotated by default to speed up apt Update, and can be uncommented if necessary
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ buster main contrib non-free
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ buster main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ buster-updates main contrib non-free
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ buster-updates main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ buster-backports main contrib non-free
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ buster-backports main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian-security buster/updates main contrib non-free
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian-security buster/updates main contrib non-free
Copy the code
Nginx is installed in the etc directory by default. Check the Nginx configuration file
cat /etc/nginx/nginx.conf
Copy the code
We look at the content of the red box finally, said using the/etc/nginx/conf. D/default. Configuration file.
Then we edit the/etc/nginx/conf. D/default. The conf file.
vi /etc/nginx/conf.d/default.conf
Copy the code
The configuration is the same as the nginx configuration above, except that we need to pass the necessary files (static files,SSL certificates) to the Docker container
Create a directory for storing resources
mkdir /data/cert
mkdir /data/www
Copy the code
Exit the Docker container and go to the server interface
exit
Copy the code
You can obtain the ids of all containers by viewing the information about them, as shown in the following figure
docker ps -a
Copy the code
Pass the resource file to the nginx container under Docker at the server terminal
docker cp /data/cert 6ba3901beac9:/data/cert
Copy the code
Save the container
Then run the following command to save the image:
Docker commit -m=" Remarks "your CONTAINER_ID your IMAGECopy the code
Please change the information after -m to the information of your own container
And we’re done!
Congratulations on finishing the Docker tutorial and learning some of the basics of Docker
Install Jenkins under Centos
Jenkins is a Continuous build tool platform developed in the Java language for continuously and automatically building/testing your software and projects. It can perform your pre-set setup and build scripts, and it can integrate with the Git code base for automatic and timed builds.
Most of the content in this section is the handling of the nugget booklet for implementing a set of CI/CD processes from 0 to 1. You can learn more about this booklet
Its installation
Because Jenkins is a continuous build platform for Java writing, Java installation is essential.
In this case, we chose to install the open source OpenJDK. Here we just installed OpenJDK using yum package manager.
yum install -y java
Copy the code
Use domestic mirroring to accelerate Jenkins installation
The official tutorial installation is too slow. So we choose domestic image installation
Below is the Jenkins LTS version (2021/04) : you can go to the mirror website of Tsinghua University and replace it with the latest link
Download Jenkins to the /data directory
CD/data wget https://mirrors.tuna.tsinghua.edu.cn/jenkins/redhat-stable/jenkins-2.277.2-1.1.noarch.rpm sudo yum install Jenkins - 2.277.2-1.1. Noarch. RPMCopy the code
Start the Jenkins
After Jenkins is installed, the startup command is registered with the system Service command. So we can just use the system service command to start Jenkins.
There are three commands available, one for start, one for restart, and one for stop.
In this case, we simply call Service Jenkins start to start Jenkins
service jenkins start
#Service Jenkins restart Restart Jenkins
#Service Jenkins restart stop Stops Jenkins
Copy the code
After the service is started, access IP:8080. If you can see the following interface, it is starting. Jenkins’ first startup time is usually longer (depending on server performance)
Initialize the Jenkins configuration
Unlock Jenkins
After Jenkins is launched, it will automatically jump to this screen (figure 2). This is the Jenkins unlock screen, and you need to enter the initial unlock password stored on the server to proceed to the next step.
When Jenkins is started, an initial password is generated. The password is stored in the server file. We can access the server to view the password content and fill in the Jenkins’ administrator password input box:
cat /var/lib/jenkins/secrets/initialAdminPassword
Copy the code
Click the Continue button to unlock Jenkins.
Download the plugin
Once unlocked, it takes you to the Plugins download page, where you need to download some of Jenkins’ features.
Because the Jenkins plugin server is in a foreign country, the speed is not ideal. We need to replace the Jenkins plug-in source of Tsinghua University before installing the plug-in, so we do not need to install the plug-in first.
The replacement method is simple. Into the server to the/var/lib/Jenkins/updates/default plugin source address within json replaced with tsinghua university, source address, will be replaced by Google baidu.
sed -i 's/http:\/\/updates.jenkins-ci.org\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' /var/lib/jenkins/updates/default.json && sed -i 's/http:\/\/www.google.com/https:\/\/www.baidu.com/g' /var/lib/jenkins/updates/default.json
Copy the code
Then click to install the recommended plug-in. Wait for the plug-in to be installed
Complete the installation
After the plug-in is installed, it is time to register the administrator account.
Configure the configuration as prompted. If the following page is displayed, the installation is successful
Test the installation
At this point, our Jenkins has been successfully launched. However, we still need to do a little bit of simple configuration for Jenkins to be able to build docker images.
Let’s go to Jenkins home -> Left Navigation -> New Task -> Freestyle Project
After creating, find build, select Add Build step, select Execute shell, and enter the following command
docker -v
docker pull node:latest
Copy the code
This command will pull a nodeJS stable image so we can test Docker availability
Once that’s saved, we’ll click Build Now on the left menu, and Jenkins will start building. Select the first (most recent) history item on the left and click console output to view the build log.
After execution, we find that the message no access. What’s going on here? Here we have to mention Unix Socket permissions under Linux
In Linux, the Unix socket belongs to the root user and requires the root permission to access it
But in Docker, Docker provides the concept of a user group. We can add the user who executes Shell to the user group named docker, then docker command can be executed normally.
The end user in Jenkins does Jenkins, so we just need to add Jenkins to the Docker user group:
Sudo gpasswd -a Jenkins docker # Add the current user to the docker user group newgrp Docker # Update the Docker user groupCopy the code
After joining, restart Jenkins:
sudo service jenkins restart
Copy the code
After Restarting Jenkins, execute the script again. In this case, the execution succeeds:
Back to the Docker image
docker images
Copy the code
You’ll find an extra Docker node image, which we installed automatically with Jenkins
Enter this Docker image
docker run -it node /bin/bash
Copy the code
Do some configuration (see previous instructions for how to do this)
npm
Configuring Taobao Source- Global installation
yarn
And configure the Taobao source
npm config set registry https://registry.npm.taobao.org
npm get registry
#It may prompt you to install it, so you don't need to install it again
npm install yarn -g
yarn config set registry http://registry.npm.taobao.org/
yarn config get registry
exit
Copy the code
Integrate Git repository sources using SSH
In this step, we use Jenkins to integrate with an external Git repository to pull and build real code. In this case, we chose Gitee(Github is too slow ๐คง) as our code source. Here we prepare a UmiJS project to demonstrate the build.
Generate public and private keys
First, let’s configure the public and private keys. This is Jenkins’ common authentication method for accessing Git private libraries. You can use the ssh-keygen command to generate public and private keys. Just perform the build on the local machine. Here’s an email address that can be changed to your own:
ssh-keygen -t rsa -C "[email protected]"
Copy the code
Step 1: Enter file in which to save the key.
This step asks you where to put your public and private key files. The default is under ~/.ssh/id_rsa, but you can optionally enter your own path. All the way back to the car.
When you’re done, you’ll get two files. Id_rsa and id_rsa.pub.
Id_rsa is the private key file, and id_rsa.pub is the corresponding public key file.
We need to configure the public key on the Git side, and use the private key to verify the identity with Git on the Jenkins side.
Configure the public key in Gitee
In Gitee, there are two ways to configure public keys: warehouse public keys and personal public keys. If the public key of the repository is configured, the public key can access only the configured repository. If a private public key is configured, all private repositories under the account can be accessed.
Here we take configuring a personal public key as an example. First open the Settings in the upper right corner and click Settings below => SSH Public Key
There is a add public key at the bottom, just fill in the information.
The title is the public key title. You can customize the title here. The public key is the id_rsa.pub file generated just now. Run the cat command to view the content of the file, fill in the input box, and save the file. Next, go to Jenkins and configure the private key
cat ~/.ssh/id_rsa.pub
Copy the code
Configure the private key in Jenkins
Back to Jenkins. In Jenkins, authentication information such as private key/password is managed as credentials, so it can be used globally. We can add our own credentials when we configure the task. Click configuration for the project and go to Source Management => Git => Repositories
In this case, the Repository URL is our Repository address. The SSH address format is [email protected]: XXX /xxx.git. You can see it in clone/Download => SSH from the repository home page
The emphasis is on the Credentials item, and here is where we choose to authenticate the Credentials. We can add a new credential authentication information by clicking the Add => Jenkins button on the right.
Clicking on it will open a popover, which is where Jenkins added the credentials. Select SSH Username with private key in the type. Then fill in the information:
ID
What is the name of this certificate in Jenkinsdescribe
: DescriptionUsername
: User name (Email)Private Key
: This is where we fill in the private key.
On the command line window, view the contents of the private key file and copy it
cat ~/.ssh/id_rsa
Copy the code
Click the Add button to copy all file contents in XXX PRIVATE KEY file (including BEGIN OPENSSH PRIVATE KEY and END OPENSSH PRIVATE KEY).
Then click the Add button to save your credentials.
After saving, select the Credentials you added in the Credentials drop-down list.
If the red no permission message is not displayed, the identity verification is successful and the user can access the system normally.
If something like the following appears, Git is not installed on the server
After the installation, it is normal to refresh the interface
yum -y install git
Copy the code
Build the mirror
Once we have our environment ready, we can start building the image. However, we need a DockerFile to build the image. So what is a DockerFile?
Write Dockerfile
What is a Dockerfile
Dockerfile is the basic description file of a Docker image, which describes the steps required to generate an image. We can also create our own image by creating a custom Dockerfile.
For example, the following steps, using Dockerfile, can be described as:
- Based on the
Nginx: 1.15
The mirror is used as the base. - Copy local
html
Folder files, into the image/etc/nginx/html
Folder. - Copy local
conf
Folder files, into the image/etc/nginx/
Folder.
FROM nginx:1.15-alpine COPY HTML /etc/nginx/ HTML COPY conf /etc/nginx/ WORKDIR /etc/nginx/ HTMLCopy the code
Once you’re done, how do you generate the image? To build an image, just use the docker build command:
docker build -t imagename:version .
Copy the code
-t: indicates that a mirrored Tag is to be created, followed by the Tag.
The tag format is image name: version. : declares the path to the dockerfile file to find. Indicates to search in the current path. The default file name is Dockerfile.
More details on DockerFile syntax can be found here
Because our image contains only one Nginx, the dockerfile content is relatively simple. All we need to do is create a new file called Dockerfile in the code root directory, enter the following, and commit it to the code base.
Vi Dockerfile FROM nginx:1.15-alpine COPY HTML /etc/nginx/ HTML COPY conf /etc/nginx/ WORKDIR /etc/nginx/ HTMLCopy the code
git add ./Dockerfile
git commit -m "chore: add dockerfile"
git push
Copy the code
Jenkins side configuration
After the code source and DockerFile are ready. Create a jenkins-shil. sh script file in the /data directory on the server
touch /data/jenkins-shll.sh
vi /data/jenkins-shll.sh
Copy the code
Add the following
#! /bin/sh -l
yarn
yarn run build
docker build -t jenkins-test .
Copy the code
Here is a simple script to install dependency => build file => build image.
#! The functions of /bin/sh -l are as follows:
If the shell command can be executed on the server, it cannot be executed in Jenkins because Jenkins did not load the global variable /etc/profile on the server
Finally, all you need to do is execute the Shell script on the Jenkins side configuration. Find the configuration for the project, then go to build => Execute Shell. Enter the following script:
sh /data/jenkins-shll.sh
Copy the code
Manually Executing tasks
After that, we’re going to manually trigger the execution. If no error is thrown, the task is executed successfully
Go back to Docker
docker images
Copy the code
As you can see, there’s another Docker image named Jenkins-test
Automate tasks
Installing a plug-in
Install the Generic Webhook Trigger Plugin (System Administration – plug-in management – Available plug-ins – search Generic Webhook)
Select and click Install Without Restart
If the optional plugin list is empty, click the advanced TAB, replace the update site URL is: http://mirror.xmission.com/jenkins/updates/update-center.json and click on the submit and obtain immediately.
Adding a trigger
The Generic Webhook Trigger Plugin is a powerful Plugin that can Trigger different build operations based on different Trigger parameters. For example, if I submit code for the master branch to the remote repository, I will perform code deployment. If I submit code for a feature branch to the remote repository, the Generic Webhook Trigger Plugin is a powerful Plugin that can Trigger different build operations based on different Trigger parameters. When the unit tests pass, they are merged into the dev branch.
Flexibility is very high, you can customize the configuration of the solution suitable for your own company, here is convenient to demonstrate that we do not make any conditional judgment, as long as there is a push will trigger.
Go to Task Configuration > Trigger Build > select Generic Webhook Trigger and save it
Git repository configuration hooks
In this example, github has the same configuration. If you go to the code cloud project home page and click Manage – Webhooks – Add, you will see a box like this.
The URL format in the figure above is http://
:
@
: port /generic-webhook-trigger/invoke
The following options trigger hooks when you perform operations in the repository. Push is the default.
- To obtain
User ID
Go to Jenkin’s System Administration -> Manage User interface to see a list of users. The User ID is found in this list.
- To obtain
API Token
Next, click the tool icon to enter the details interface, find API Token-> Add new Token-> Generate -> find a place you like to save this Token
- Access to the port
The Jenkins IP address and port are the IP address where you deployed the Jenkins server. If the port number is not changed, it would be 8080.
- To get the password
The password is the one you use to log into Jenkins
Click Submit to complete the configuration. We also need to test whether the hook works
Click test, and if the configuration is successful, a task will appear in the Build execution status on the left side of your Jenkins column.
Implement email reminder -todo
Delete build history in batches
Go to System Configuration -> Script Command
Input script
# "test"Is the project name. 100 indicates that all (0~ยท100) are deleted, which is the ID before the build history
def jobName = "test"
def maxNumber = 100
Jenkins.instance.getItemByFullName(jobName).builds.findAll {it.number <= maxNumber}.each { it.delete() }
Copy the code
Click on the run
The last
What other Centos configurations do you use in your daily work? Feel free to leave your thoughts in the comments section!
Feel the harvest of friends welcome to like, follow a wave!
Past oliver
- What front-end developers need to know about the JS/React specification in 2021
- You have a quick check of ECMAScript features
- As a front end, what you should know about resolution/logical pixels/physical pixels/Retina display ๐ง
Reference documentation
- How To Install Node.js on CentOS 8
- How to Set Up SSH Keys on CentOS 8
- How to configure build tools (Gradle, Yarn) in Jenkins and use them in Jenkinsfile ๐
- Build the Docker environment
- Build the Nginx static website
- Set up the Node.js environment
- Field note: Jenkins builds powerful front-end automation workflows
- Implement a CI/CD process from 0 to 1
- CentOS8 installation MySQL8