Docker from entry to drop: building SpringBoot microservices based on docker

Keywords: Java Docker MySQL Maven SpringBoot

This is the second chapter from the introduction to Docker: building SpringBoot microservices based on Docker. You'd better read it before Docker from entry to drop After that, read this article.

In the previous article, I introduced how to deploy some common basic environments based on the docker container, such as MySQL and Redis. In this article, I will introduce how to package and run spring boot into the docker container.

First, introduce the basic environment to be prepared:

1. A centos machine

docker runs on centos7, which requires 64 bit system and Linux kernel version above 3.10

docker runs on CentOS 6.5 or higher, which requires 64 bit system and 2.6.32-431 or higher kernel

How to view the kernel version of the current system can be queried through the uname instruction:

[root@izwz9ic9ggky8kub9x1ptuz target]# uname -r
3.10.0-514.26.2.el7.x86_64
[root@izwz9ic9ggky8kub9x1ptuz target]#

 

2. A basic spring boot project code

First, let's build a simple springboot template project. Here is the related dependency file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sise</groupId>
    <artifactId>docker-springboot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <properties>
        <docker.image.prefix>springboot</docker.image.prefix>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


    <build>
        <!-- Note that the name here should be written with the following DockerFile Consistent naming in -->
        <finalName>spring-boot-docker-1.0</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- Docker maven plugin -->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <dockerDirectory>src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
            <!-- Docker maven plugin -->
        </plugins>
    </build>

</project>

 

Note that there are several configuration points to pay close attention to. In the maven configuration above, there is an attribute configuration called dockerDirectory:

               <configuration>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <dockerDirectory>src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>

 

This property corresponds to the location where the Dockerfile file is stored:


Note the pit:

In the directory of src/main/docker, we need to write a file called Dockerfile. Note that the name of this Dockerfile must not be modified, otherwise it will not be recognized, causing the following exception to be thrown:

Failed to execute goal com.spotify:docker-maven-plugin:1.0.0:build (default-cli) on project docker-springboot:
Exception caught: Request error: POST unix://localhost:80/build?t=springboot%2Fdocker-springboot: 500, body:
{"message":"Cannot locate specified Dockerfile: Dockerfile"}: HTTP 500 Internal Server Error -> [Help 1]

 

This Dockerfile needs to be written with special syntax rules. Here I give a basic Dockerfile template:

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD spring-boot-docker-1.0.jar app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

 

Explain the semantic meaning here:

FROM [image] refers to other image information that needs to be relied on. jdk image is selected here

For unfamiliar image environments, if you need to search, you can go to the official website of docker to view:
https://hub.docker.com/

Insert picture description here

ADD source address target address means to ADD the original src file to the image we need to package

The default working directory created by the VOLUME /tmp Spring Boot application for Tomcat. The function is to create a temporary file in your host's "/ var/lib/docker" directory and link it to the "/ tmp" directory in the container. The contents of this part can be viewed in detail in the corresponding directory:

[root@izwz9ic9ggky8kub9x1ptuz docker]# cd /var/lib/docker
[root@izwz9ic9ggky8kub9x1ptuz docker]# ls
builder  buildkit  containers  image  network  overlay2  plugins  runtimes  swarm  tmp  trust  volumes
[root@izwz9ic9ggky8kub9x1ptuz docker]# cd ./tmp/
[root@izwz9ic9ggky8kub9x1ptuz tmp]# ls
docker-builder661781695
[root@izwz9ic9ggky8kub9x1ptuz tmp]# cd docker-builder661781695/
[root@izwz9ic9ggky8kub9x1ptuz docker-builder661781695]# ls
dockerFile  docker-springboot-1.0-SNAPSHOT.jar
[root@izwz9ic9ggky8kub9x1ptuz docker-builder661781695]# 

 

ENTRYPOINT this instruction means the command content transferred by default when the application is executed.

The code of SpringBoot is also relatively simple, which is the Application startup class:

package com.sise.docker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author idea
 * @data 2019/11/10
 */
@SpringBootApplication
public class DockerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DockerApplication.class);
    }
}

 

And the corresponding spring boot controller:

package com.sise.docker.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author idea
 * @data 2019/11/10
 */
@RestController
@RequestMapping(value = "/docker")
public class DockerController {

    @GetMapping(value = "/test")
    public String test(){
        return "this is docker test";
    }
}

 

application.yml file information:

server:
  port: 7089

 

3. maven and docker environments need to be installed on the server

About the installation of docker environment, I have explained it in the previous article. If I haven't read the previous article, click here: Docker from entry to drop.

maven environment installation instructions:

First, you need to select the installation address on your machine, then download the corresponding file package and extract it:

wget http://mirrors.hust.edu.cn/apache/maven/maven-3/3.1.1/binaries/apache-maven-3.1.1-bin.tar.gz
tar zxf apache-maven-3.1.1-bin.tar.gz

 

Then we configure the corresponding environment variables:

export MAVEN_HOME=[maven Installation path for]
export PATH=$PATH:$JAVA_HOME/bin:$MAVEN_HOME/bin

 

Remember to refresh the profile Profile

source /etc/profile

Finally, verify whether maven configuration is normal:

[root@izwz9ic9ggky8kub9x1ptuz docker]# mvn -version
Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 23:22:22+0800)
Maven home: /opt/maven/apache-maven-3.1.1
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: /opt/jdk/jdk1.8.0_151/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-514.26.2.el7.x86_64", arch: "amd64", family: "unix"

 

Now that everything is ready, let's upload a prepared spring boot project to the centos machine, and package it with the command of maven:

mvn package docker:build

When the construction is successful, the following information will appear:

[INFO] Built springboot/spring-boot-docker
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 54.346 s
[INFO] Finished at: 2018-03-13T16:20:15+08:00
[INFO] Final Memory: 42M/182M
[INFO] ------------------------------------------------------------------------

 

Then we can view the current image content through the familiar docker images command:

Finally, start our image file and test it:

[root@izwz9ic9ggky8kub9x1ptuz springboot-docker]# docker run -p 7089:7089 -d springboot/docker-springboot
38ec31c7a4802d852ee0834e1773136bd58a255875a9fa8cb2898aef0daa3e51
[root@izwz9ic9ggky8kub9x1ptuz springboot-docker]#

 

After the startup is successful, we test the interface through the command:

[root@izwz9ic9ggky8kub9x1ptuz springboot-docker]# curl 127.0.0.1:7089/docker/test
this is docker test
[root@izwz9ic9ggky8kub9x1ptuz springboot-docker]# 

 

Well, a basic spring boot container based on docker container running will come to an end.

Written at the end of the article

At the end of the article, I intend to continue Some shortcomings mentioned in the previous article I'm here to add:
According to the questions raised by @ ancient name readers, there is no official introduction to docker image:

When we need to query some special images, there are two ways to search for information about images. One is to search images directly on the official website, and the other is to search images through docker search.

The first way is to enter the https://hub.docker.com official website, and then search in the search bar at the top. For example, if we want to search image information about mysql, we can do the following:

 

The results of searching on the official website are basically the same as those of executing "docker search" on the command line:

 

[root@izwz9ic9ggky8kub9x1ptuz springboot-docker]# docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation...   8787                [OK]                
mariadb                           MariaDB is a community-developed fork of MyS...   3080                [OK]                
mysql/mysql-server                Optimized MySQL Server Docker images. Create...   652                                     [OK]
percona                           Percona Server is a fork of the MySQL relati...   459                 [OK]                
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   64                                      
centurylink/mysql                 Image containing mysql. Optimized to be link...   61                                      [OK]
mysql/mysql-cluster               Experimental MySQL Cluster Docker images. Cr...   56                                      
deitch/mysql-backup               REPLACED! Please use http://hub.docker.com/r...   41                                      [OK]
bitnami/mysql                     Bitnami MySQL Docker Image                      35                                      [OK]
tutum/mysql                       Base docker image to run a MySQL database se...   34                                      
schickling/mysql-backup-s3        Backup MySQL to S3 (supports periodic backup...   28                                      [OK]
prom/mysqld-exporter                                                              23                                      [OK]
linuxserver/mysql                 A Mysql container, brought to you by LinuxSe...   22                                      
centos/mysql-56-centos7           MySQL 5.6 SQL database server                   17                                      
circleci/mysql                    MySQL is a widely used, open-source relation...   16                                      
mysql/mysql-router                MySQL Router provides transparent routing be...   14                                      
arey/mysql-client                 Run a MySQL client from a docker container      13                                      [OK]
imega/mysql-client                Size: 36 MB, alpine:3.5, Mysql client: 10.1....   9                                       [OK]
openshift/mysql-55-centos7        DEPRECATED: A Centos7 based MySQL v5.5 image...   6                                       
fradelg/mysql-cron-backup         MySQL/MariaDB database backup using cron tas...   4                                       [OK]
genschsa/mysql-employees          MySQL Employee Sample Database                  2                                       [OK]
ansibleplaybookbundle/mysql-apb   An APB which deploys RHSCL MySQL                2                                       [OK]
jelastic/mysql                    An image of the MySQL database server mainta...   1                                       
widdpim/mysql-client              Dockerized MySQL Client (5.7) including Curl...   0                                       [OK]
monasca/mysql-init                A minimal decoupled init container for mysql    0   

 

You may wonder why there are so many related information after entering MySQL keywords. In fact, this is a full-text search, which will uniformly query out some image information that contains MySQL in the description.

If we need to select a certain image of MySQL for download, we can directly docker pull mysql, but in this way, the latest version of the image will be pulled to the host. If there is a requirement for the version, we can select the appropriate version on the official website to pull it.


In the picture, I also circle the command to pull the image of different versions.

Please don't panic about the question of docker visual management tool asked by readers.

In fact, there are many visualized management tools for docker: shipyard, docker UI, Porter, Rancher, etc

I suggest that it is better to use the command line as a beginner, and that visualization tools actually weaken the hands-on ability of developers. The main purpose of using visualization tools is to improve work efficiency and reduce the difficulty of practical operation.

Posted by darkside_3k on Tue, 12 Nov 2019 21:40:36 -0800