This tutorial focuses on deploying front-end projects using Jenkins and Github Actions.
- The first part is to use Gitea to configure the GIT server on the LAN, and then use Jenkins to deploy the project under Gitea to the LAN server.
- The second part is to use Github Actions to deploy the Github project to the Github Page and the Ari Cloud.
No prior knowledge of Jenkins and Github Actions is required to follow this tutorial to automate your deployment projects.
PS: THE operating system of my computer is Windows, that is, all the following operations are run under Windows. The configuration of other operating systems is pretty much the same, not much different.
Gitea + Jenkins automatically builds front-end projects and deploys them to the server
Gitea is used to build Git LAN servers, and Jenkins is a CI/CD tool for deploying front-end projects.
Configuration Gitea
- downloadGitea, select a preferred version, such as 1.13, select
Gitea - 1.13 - Windows - 4.0 - amd64. Exe
Download. - After downloading, create a new directory (for example, Gitea), place the downloaded Gitea software in this directory, and double-click to run it.
- Open the
localhost:3000
You should see Gitea already running on your computer. - Click Register, the first time will pop up an initial configuration page, database selection
SQLite3
. In addition tolocalhost
Change your computer’s LAN address, for example, my computer’s IP address to192.168.0.118
.
5. After completing the configuration, click Install Now and wait for a while. 6. Continue to click register user, the first user to register will become the administrator. 7. Go to the Gitea installation directory, go to Custom \conf\app.ini, and add START_SSH_SERVER = true. Now you can use SSH for push.
8. If the project cannot be cloned using HTTP, cancel the Git proxy.
git config --global --unset http.proxy
git config --global --unset https.proxy
Copy the code
Configuration Jenkins
- Need to install JDK in advance, JDK installation tutorial online many, please search.
- Open the Jenkins download page.
- Encountered during installation
Logon Type
“, select the first one.
- The default port is 8080, so I said 8000. It will open automatically after installation
http://localhost:8000
Site, then need to wait for a while, initialization. - Follow the instructions to find the corresponding file (direct copy path in my computer to open), which has the administrator password.
6. Install the plug-in and select the first one.
- To create an administrator, click Finish and save, then go to the next step.
8. Click Manage Jenkins -> Manage Plugins to install the plugin.
9. Click Optional plug-ins, type Nodejs, search for plug-ins, and install. 10. Once installed, go back to the home page and configure NodeJS by clicking Manage Jenkins -> Global Tool Configuration. If you are running Windows 7, the nodeJS version should not be too high and should be around V12.
Creating a Static server
- Create an empty directory from which to execute
npm init -y
Initializes the project. - perform
npm i express
Download the express. - And then create a
server.js
File with the following code:
const express = require('express')
const app = express()
const port = 8080
app.use(express.static('dist'))
app.listen(port, () = > {
console.log(`Example app listening at http://localhost:${port}`)})Copy the code
It sets the dist folder in the current directory to the static server resources directory, and then executes Node Server.js to start the server.
The site is empty because there is no dist folder now.
But don’t worry, you’ll see it in a minute.
Automatic build + deploy to server
- Download Jenkins’ demo building- A – Multibranch – Pipeline – Project, then create a new repository in your Gitea, clone it and submit it to the Gitea server.
- Open the Jenkins home page and click
The new Item
Create the project.
- choose
Source code management
, enter the warehouse address on your Gitea.
- You can also try a timed build, which the following code shows every 5 minutes.
- Select your build environment, in this case the nodeJS you just configured.
- Click Add Build Step, Windows to select
execute windows batch command
Linux to chooseexecute shell
.
- The input
npm i && npm run build && xcopy .\build\* G:\node-server\dist\ /s/e/y
, which installs dependencies, builds the project, and copies the built static resources to the specified directoryG:\node-server\dist\
. This directory is the static server resource directory.
- After saving the Settings, return to the home page. Click the small triangle next to the item and select
build now
.
- To start building the project, we can click on the project to see the build process.
- Build successful, open
http://localhost:8080/
Look at the results.
- Since we set it to build every 5 minutes, we can change the content of the site, do nothing and wait for a while to open the site.
- Submit the changes to the Gitea server, wait a moment. Open the site and find that the content has changed.
Build the project using pipeline
Pipelining projects can be combined with Gitea’s Webhook hooks to automatically build projects when a Git push is performed.
- Click on the username in the upper right corner of the homepage and select
Set up the
.
- Add the token and remember to save the token.
- Open the Jenkins home page and click
The new Item
Create the project.
- Click on the
Build trigger
, the choice ofTriggering a remote build
, fill in the token you just created.
5. Select pipeline, enter the content as prompted, and click Save.
6. Open the jenkins. XML file in the Jenkins installation directory and find the
tag. Add – Dhudson. In security. CSRF. GlobalCrumbIssuerConfiguration. DISABLE_CSRF_PROTECTION = true. It turns off CSRF validation, and Gitea’s Webhook will keep reporting 403 errors. After the parameters are added, enter Jenkins. Exe restart to restart Jenkins.
7. Return to the home page and configure global security options. Check that the anonymous user has read permission and save.
- Open your Gitea repository page and select
The warehouse is set
.
- Click on the
Managing Web Hooks
, add web hook, hook option selectionGitea
. - Enter the target URL as Jenkins prompts. And then click
Adding a Web Hook
.
- Click the created Web hook, drag it down, and click Test Push. No surprise, you should be able to see the success of the push message, at this point back to Jenkins home page, found that the project is already under construction.
- Because there is no configuration
Jenkinsfile
File, at which point the build will not succeed. So you need to configure itJenkinsfile
File. Copy the following code to your Gitea projectJenkinsfile
File. Jenkins will automatically read the contents of the file to perform build and deployment operations during build.
Pipeline {agent any stages {stage('Build') {steps {// window uses bat, Linux uses sh bat 'NPM I' bat 'NPM run build'}} stage('Deploy') {steps {bat 'xcopy.\\build\ * D: \ \ node - server \ \ dist \ \ / s/e/y '/ / need to here your static server resource directory}}}}Copy the code
- Whenever your Gitea project is executed
push
When you operate, Gitea will passwebhook
Send a POST request to Jenkins to perform the build and deploy operations.
summary
If your operating system is Linux, you can use SSH to log in to Ali Cloud after Jenkins is packaged and copy the packaged files to the static server on Ali Cloud, so that ali Cloud automatic deployment can be realized. For details on how to remotely log in to Ali Cloud, see the section “Github Actions Deployed to Ali Cloud” below.
Github Actions automatically builds front-end projects and deploits them to the server
If your project is a Github project, then using Github Actions might be a better choice.
Deploy to Github Page
Next, take a look at how to deploy to a Github Page using Github Actions.
Create a YML file for the project you need to deploy to the Github Page and put it in the.github/ Workflow directory. You can call it ci.yml, which is similar to Jenkins’ Jenkinsfile, and contains the script code to be automatically executed.
The contents of this YML file are as follows:
name: Build and Deploy
on: # listen for push events on the master branch
push:
branches:
- master
jobs:
build-and-deploy:
runs-on: ubuntu-latest # Build the environment using Ubuntu
steps:
- name: Checkout
uses: The actions/[email protected]
with:
persist-credentials: false
- name: Install and Build Download depends on the package project
run: | npm install npm run build
- name: Deploy # Post packaged content to Github Page
uses: JamesIves/[email protected] # Use actions written by others
with: # Customize environment variables
ACCESS_TOKEN: The ${{ secrets.VUE_ADMIN_TEMPLATE }} # VUE_ADMIN_TEMPLATE is my secret name and needs to be replaced with yours
BRANCH: master
FOLDER: dist
REPOSITORY_NAME: woai3c/woai3c.github.io # This is my Github Page repository
TARGET_FOLDER: github-actions-demo # Packed files will be placed in the static server github-actions-demo directory
Copy the code
There is an ACCESS_TOKEN variable above that you need to configure yourself.
- Go to Github, click on your avatar in the upper right corner, and select
settings
.
- Click on the bottom left corner
developer settings
.
- In the left sidebar, click
Personal Access Tokens
.
- Click on the
Generate new token
.
- Enter a name and check it
repo
.
- Drag it to the bottom and click
Generate token
And save the generated token.
- Open your Github project and click
settings
.
Click secrets-> New Secret.
Create a key with an arbitrary name (separated by underscores) and the contents of the token you just created.
ACCESS_TOKEN: ${{secrets.vue_admin_template}} ACCESS_TOKEN: ${{secrets.vue_admin_template}} The ${{secrets. TEST_A_B}} instead! Save it and submit it to Github.
Github Actions will automatically build your project and post it to your Github Page as soon as you do a Git push.
For details of Github Actions, click the Actions option in the repository.
For details, please refer to my github- Actions -demo project.
After the build, open the Github Page and find that the content has been published successfully.
Github Actions deployed to Ali Cloud
Initialize ali Cloud server
- Buy Ali cloud server, choose operating system, I choose Ubuntu
- On the Cloud server management Console, choose Instance -> More -> Key -> Reset instance password (later login)
- Select Remote connection ->VNC, a password will pop up, remember it, in the future remote connection to use (CTRL + Alt + F1 ~ F6 switch terminal, such as CTRL + Alt + F1 is the first terminal)
- You enter a command line input
root
(default username), password is the instance password you just reset - Login successful, update the installation source
sudo apt-get update && sudo apt-get upgrade -y
- Install the NPM
sudo apt-get install npm
- Install the NPM management package
sudo npm install -g n
- Install the latest stable version of Node
sudo n stable
Create a static server
mkdir node-server // Create the node-server folder
cd node-server // Go to the node-server folder
npm init -y // Initialize the project
npm i express
touch server.js // Create the server.js file
vim server.js // Edit the server.js file
Copy the code
Enter the following code (enter the file using vim and press I to edit it, save the file by pressing Esc and then enter :wq, then press Enter), and search for more ways to use it.
const express = require('express')
const app = express()
const port = 3388 // Add your own ali cloud mapping port to the network security group.
app.use(express.static('dist'))
app.listen(port, '0.0.0.0'.() = > {
console.log(`listening`)})Copy the code
Execute node server.js to start listening. Since there is no dist directory, don’t worry.
Note that the listening IP address must be 0.0.0.0. For details, see Precautions for deploying Node.js.
The ali cloud inbound port should be viewed and configured in the network security group.
Create ali Cloud key pair
See Creating and Binding SSH Key Pairs to bind your ECS server instance to the key and then save the private key to your computer (for example, in an ECs.pem file).
To open the Github project you want to deploy to AliYun, click Setting -> Secrets.
Click new secret
Secret name is SERVER_SSH_KEY, and the ali cloud key just filled in the content.
Click Add Secret to finish.
Create a.github workflows ci.yml file under your project and fill in the following:
name: Build app and deploy to aliyun
on:
# listen for push
push:
branches:
# master branch, you can change it to another branch
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install Node.js
uses: actions/setup-node@v1
with:
node-version: '12.16.2'
- name: Install npm dependencies
run: npm install
- name: Run build task
run: npm run build
- name: Deploy to Server
uses: Easingthemes/[email protected]
env:
SSH_PRIVATE_KEY: The ${{ secrets.SERVER_SSH_KEY }}
ARGS: '-rltgoDzvO --delete'
SOURCE: dist # This is the folder name to copy to ali Cloud static server
REMOTE_HOST: '118.190.217.8' # Your Aliyun public address
REMOTE_USER: root # Alicloud login default user root, and the folder is root
TARGET: /root/node-server The dist folder will be placed in /root/node-server
Copy the code
Save and push to Github.
In the future, whenever your project performs git push, the script defined by Ci.yml will be automatically executed to place the package file on your Aliyun static server.
This action does two things:
- Clone your project, download dependencies, and pack them.
- Log in to Ali Cloud by SSH with your Ali cloud private key and upload the packaged files (using rsync) to the folder specified by Ali Cloud.
If you still don’t understand, I suggest you take a look at my demo.
ci.yml
Configuration File Description
name
Represents the name of the workflow.on
“, and can be followed by various events, e.gpush
Events.
The following code represents listening for a push event on the master branch. When Github Actions listens for a push event, it performs a series of Actions defined by Jobs below.
name: Build app and deploy to aliyun
on:
# listen for push
push:
branches:
# master branch, you can change it to another branch
- master
jobs:
.
Copy the code
jobs
“, literally means a series of homework that you can do injobs
A number of jobs are defined under the fields, for examplejob1
,job2
And so on, and they’re executed in parallel.
jobs:
job1:
.
job2:
.
job3:
.
Copy the code
If you look back at the ci.yml file, it has only one job, build. The name of the job is your own, and you can call it good.
runs-on
, indicating what operating system your workflow is running on,ci.yml
The file defined is the latest stable versionubuntu
. In addition to Ubuntu, it can also be selected for Mac or Windows.
steps
A series of steps this assignment is a series of steps. For example, execute firststep1
And then to performstep2
.
setps
Step on
Setps is actually an array, which in YAML syntax starts with – as an array item. For example [‘a’, ‘b’, ‘c’] is expressed using YAML syntax:
- a
- b
- c
Copy the code
So SETPS is an array of steps, executed from top to bottom. From the ci.yml file, there are several related options for each small step:
name
, the name of the small step.uses
Github Actions allows you to use actions libraries written by others.run
, small steps to performshell
Command.env
, set the environment variables associated with the small step.with
, provide parameters.
In summary, the setps in ci.yml file is easy to understand, so let’s explain from beginning to end:
steps:
- uses: actions/checkout@v1
- name: Install Node.js
uses: actions/setup-node@v1
with:
node-version: '12.16.2'
- name: Install npm dependencies
run: npm install
- name: Run build task
run: npm run build
- name: Deploy to Server
uses: Easingthemes/[email protected]
env:
SSH_PRIVATE_KEY: The ${{ secrets.SERVER_SSH_KEY }}
ARGS: '-rltgoDzvO --delete'
SOURCE: dist # This is the folder name to copy to ali Cloud static server
REMOTE_HOST: '118.190.217.8' # Your Aliyun public address
REMOTE_USER: root # Alicloud login default user root, and the folder is root
TARGET: /root/node-server The dist folder will be placed in /root/node-server
Copy the code
- use
actions/checkout@v1
Library clone code toubuntu
On. - use
actions/setup-node@v1
Install nodeJS library,with
A parameter is providednode-version
Represents the nodeJS version to install. - in
ubuntu
的shell
Performed on thenpm install
Download dependencies. - perform
npm run build
Package projects. - use
Easingthemes/[email protected]
Library. That’s what this library doesSSH
Remote login to ali Cloud server, copy the packaged folder to the directory specified by Ali Cloud.
As you can see from env, the actions library requires us to provide several environment variables:
SSH_PRIVATE_KEY
: Ali cloud key pair of private key (need you to write in advance on Github secrets),ARGS: '-rltgoDzvO --delete'
I guess I copied the file and then deleted it.SOURCE
: Indicates the folder name after packagingREMOTE_HOST
: Public IP address of Ali CloudREMOTE_USER
: User name of ali cloud serverTARGET
: you want to copy to ali cloud server specified directory name
If you want to see another implementation of the actions library, you can simply copy the name of the Actions library and go to the search engine. For example, search actions/checkout will result in:
Now that you’ve seen it, give it a thumbs up before you go.
The resources
- Jenkins User Manual
- Making Actions document
- Making Pages document
- Gitea document
- Workflow syntax for GitHub operations