This tutorial focuses on deploying front-end projects using Jenkins and Github Actions.

  1. 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.
  2. 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

  1. downloadGitea, select a preferred version, such as 1.13, selectGitea - 1.13 - Windows - 4.0 - amd64. ExeDownload.
  2. After downloading, create a new directory (for example, Gitea), place the downloaded Gitea software in this directory, and double-click to run it.
  3. Open thelocalhost:3000You should see Gitea already running on your computer.
  4. Click Register, the first time will pop up an initial configuration page, database selectionSQLite3. In addition tolocalhostChange 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

  1. Need to install JDK in advance, JDK installation tutorial online many, please search.
  2. Open the Jenkins download page.

  1. Encountered during installationLogon Type“, select the first one.

  1. The default port is 8080, so I said 8000. It will open automatically after installationhttp://localhost:8000Site, then need to wait for a while, initialization.
  2. 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.

  1. 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

  1. Create an empty directory from which to executenpm init -yInitializes the project.
  2. performnpm i expressDownload the express.
  3. And then create aserver.jsFile 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

  1. 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.

  1. Open the Jenkins home page and clickThe new ItemCreate the project.

  1. chooseSource code management, enter the warehouse address on your Gitea.

  1. You can also try a timed build, which the following code shows every 5 minutes.

  1. Select your build environment, in this case the nodeJS you just configured.

  1. Click Add Build Step, Windows to selectexecute windows batch commandLinux to chooseexecute shell.

  1. The inputnpm 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.

  1. After saving the Settings, return to the home page. Click the small triangle next to the item and selectbuild now.

  1. To start building the project, we can click on the project to see the build process.

  1. Build successful, openhttp://localhost:8080/Look at the results.

  1. 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.

  1. 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.

  1. Click on the username in the upper right corner of the homepage and selectSet up the.

  1. Add the token and remember to save the token.

  1. Open the Jenkins home page and clickThe new ItemCreate the project.

  1. Click on theBuild 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.

  1. Open your Gitea repository page and selectThe warehouse is set.

  1. Click on theManaging Web Hooks, add web hook, hook option selectionGitea.
  2. Enter the target URL as Jenkins prompts. And then clickAdding a Web Hook.

  1. 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.

  1. Because there is no configurationJenkinsfileFile, at which point the build will not succeed. So you need to configure itJenkinsfileFile. Copy the following code to your Gitea projectJenkinsfileFile. 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
  1. Whenever your Gitea project is executedpushWhen you operate, Gitea will passwebhookSend 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.

  1. Go to Github, click on your avatar in the upper right corner, and selectsettings.

  1. Click on the bottom left cornerdeveloper settings.

  1. In the left sidebar, clickPersonal Access Tokens.

  1. Click on theGenerate new token.

  1. Enter a name and check itrepo.

  1. Drag it to the bottom and clickGenerate tokenAnd save the generated token.

  1. Open your Github project and clicksettings.

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

  1. Buy Ali cloud server, choose operating system, I choose Ubuntu
  2. On the Cloud server management Console, choose Instance -> More -> Key -> Reset instance password (later login)
  3. 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)
  4. You enter a command line inputroot(default username), password is the instance password you just reset
  5. Login successful, update the installation sourcesudo apt-get update && sudo apt-get upgrade -y
  6. Install the NPMsudo apt-get install npm
  7. Install the NPM management packagesudo npm install -g n
  8. Install the latest stable version of Nodesudo 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:

  1. Clone your project, download dependencies, and pack them.
  2. 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.ymlConfiguration File Description

  1. nameRepresents the name of the workflow.
  2. on“, and can be followed by various events, e.gpushEvents.

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
  1. jobs“, literally means a series of homework that you can do injobsA number of jobs are defined under the fields, for examplejob1,job2And 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.

  1. runs-on, indicating what operating system your workflow is running on,ci.ymlThe file defined is the latest stable versionubuntu. In addition to Ubuntu, it can also be selected for Mac or Windows.

  1. stepsA series of steps this assignment is a series of steps. For example, execute firststep1And then to performstep2.

setpsStep 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:

  1. name, the name of the small step.
  2. usesGithub Actions allows you to use actions libraries written by others.
  3. run, small steps to performshellCommand.
  4. env, set the environment variables associated with the small step.
  5. 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
  1. useactions/checkout@v1Library clone code toubuntuOn.
  2. useactions/setup-node@v1Install nodeJS library,withA parameter is providednode-versionRepresents the nodeJS version to install.
  3. inubuntushellPerformed on thenpm installDownload dependencies.
  4. performnpm run buildPackage projects.
  5. useEasingthemes/[email protected]Library. That’s what this library doesSSHRemote 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:

  1. SSH_PRIVATE_KEY: Ali cloud key pair of private key (need you to write in advance on Github secrets),
  2. ARGS: '-rltgoDzvO --delete'I guess I copied the file and then deleted it.
  3. SOURCE: Indicates the folder name after packaging
  4. REMOTE_HOST: Public IP address of Ali Cloud
  5. REMOTE_USER: User name of ali cloud server
  6. TARGET: 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