Deploy Java projects using GitHub Actions

Create action file

Create the.github/workflows folder in the root directory of the project and add the corresponding YML file, for example:

|   .github
|       workflows
|           maven.yml
Copy the code

Writing CI files

Example CI file is as follows:

name: Build Ci

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up JDK 1.8
        uses: actions/setup-java@v1
        with:
          java-version: 1.8
    
      # Set maven cache
      - name: Cache Maven packages
        uses: actions/cache@v1
        with:
          path: ~/.m2
          key: The ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
          restore-keys: The ${{ runner.os }}-m2

      - name: Maven Build
        run: mvn -B package   -DskipTests --file pom.xml

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1

     # set the account password of hub.docker. IO
      - name: Login to DockerHub
        uses: docker/login-action@v1
        with:
            username: The ${{ secrets.DOCKERHUB_USERNAME }}
            password: The ${{ secrets.DOCKERHUB_TOKEN }}

     Package to DockerHub
      - name: Push to Docker
        uses: docker/build-push-action@v2
        with:
            context: .
            file: ./Dockerfile
            push: true
            tags: | ${{ secrets.DOCKERHUB_USERNAME }}/wkserver:latestCopy the code

Set the cache

To avoid pulling maven dependencies every time you package, you can set your project’s dependency cache based on the POM file hash as follows:

- name: Cache Maven packages
      uses: actions/cache@v1
      with:
      path: ~/.m2
      key: The ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
      restore-keys: The ${{ runner.os }}-m2
Copy the code

Packaging to the Docker

Use the Action plugin to package the DockerFile into the hub.

Configuration variables

Open the github homepage and go to “Seeting” -> “secrets” -> “New Respository Secret”

See the effect

Modify the project code to trigger the Github Actions job, and you can see that github Actions is executing the task as written

After the command is executed, you can go to the Docker Hub to view the docker image

At this point, we have successfully used Docker Actions to complete the image packaging of the Java program