Java Application Configuration container health check docker environment

In the "speed experience docker container healthy" one article has experienced docker container health checks, today came to the container java application to join the health check, the status of the application at any time can be monitored and viewed.

Combat environmental information

  1. Operating System: macOS Catalina 10.15
  2. Docker:19.03.2

java Application Brief

Today's real java application, is used to simulate the production environment applications, features are as follows:

  1. General springboot applications, provide external http service, path: / the Hello
  2. springboot applications running in the docker container, the container's / app / depend / have named directory abc.txt documents;
  3. Abc.txt the above file exists, springboot hello application interface is normal, if there is no abc.txt, springboot application does not provide services, equivalent to an unhealthy state (in order to simulate application abnormal);

Source download

If you do not want to write code for the springboot application source code can be downloaded from GitHub, address and link information in the following table:

name link Remark
Project Home https://github.com/zq2599/blog_demos The project's home page on GitHub
git repository address (https) https://github.com/zq2599/blog_demos.git The project's source code repository address, https protocol
git repository address (ssh) [email protected]:zq2599/blog_demos.git The project's source code repository address, ssh protocol

The git item has multiple folders in the application of this chapter springboot-app-docker-health- check folder file, as shown in FIG red box:
Here Insert Picture Description

Step Introduction

The step of applying the access vessel health check as follows:

  1. Required base image, and therefore ready to be made into a java application when the docker good mirror base image, health check of the container parameters are arranged in the base image, the container includes an interface path provides health information, as where / getState ;
  2. Transformation java applications, providing / getstate interface services, decided to return to the current application code 200 is healthy, health, the return code is 403 when the unhealthy according to the actual situation of the business;
  3. And generating a compiled application build docker mirror;
  4. verification;

Production base image

  1. Create a file named Dockerfile file, as follows:
# Docker file from bolingcavalry # VERSION 0.0.1
# Author: bolingcavalry

#基础镜像
FROM openjdk:8-jdk-stretch

#作者
MAINTAINER BolingCavalry <[email protected]>

#健康检查参数设置,每5秒检查一次,接口超时时间2秒,连续10次返回1就判定该容器不健康
HEALTHCHECK --interval=5s --timeout=2s --retries=10 \
  CMD curl --silent --fail localhost:8080/getstate || exit 1

The contents of which are visible Dockerfile very simple, self-selected base image is openjdk: the Stretch-8-the JDK , and then configure the health check parameters:

parameter name effect
health-cmd Specify the command execution within the container, the container for checking health status
health-interval Every health check interval, default 30 seconds
health-retries Assuming that the value is 3, indicating that if three consecutive detection result returned is unhealthy, it is determined that the healthy vessel, the default value is 3
health-timeout Timeout, default 30 seconds
  1. In Dockerfile file directory Run Docker Build -t bolingcavalry / jdk8-Healthcheck:. 0.0.1 (the last point of that number do not miss), the console output is as follows, indicating successfully constructed image:
(base) zhaoqindeMacBook-Pro:springboot-app-docker-health-check zhaoqin$ docker build -t bolingcavalry/jdk8-healthcheck:0.0.1 .
Sending build context to Docker daemon  217.6kB
Step 1/3 : FROM openjdk:8-jdk-stretch
8-jdk-stretch: Pulling from library/openjdk
9a0b0ce99936: Already exists
db3b6004c61a: Already exists
f8f075920295: Already exists
6ef14aff1139: Already exists
962785d3b7f9: Already exists
631589572f9b: Already exists
c55a0c6f4c7b: Already exists
Digest: sha256:8bce852e5ccd41b17bf9704c0047f962f891bdde3e401678a52d14a628defa49
Status: Downloaded newer image for openjdk:8-jdk-stretch
 ---> 57c2c2d2643d
Step 2/3 : MAINTAINER BolingCavalry <[email protected]>
 ---> Running in 270f78efa617
Removing intermediate container 270f78efa617
 ---> 01b5df83611d
Step 3/3 : HEALTHCHECK --interval=5s --timeout=2s --retries=10   CMD curl --silent --fail localhost:8080/getstate || exit 1
 ---> Running in 7cdd08b9ca22
Removing intermediate container 7cdd08b9ca22
 ---> 9dd7ffb22df4
Successfully built 9dd7ffb22df4
Successfully tagged bolingcavalry/jdk8-healthcheck:0.0.1
  1. At this time, the host name already bolingcavalry / jdk8-healthcheck: 0.0.1 mirror, the mirror with the health check the parameters of the container, as a basis to construct a mirror image of the other characteristics are integrated health check ;
  2. 如果您已经在hub.docker.com上注册过,就可以用docker login命令登录,然后执行以下命令将本地镜像推送到hub.docker.com给更多人使用:
docker push bolingcavalry/jdk8-healthcheck:0.0.1

改造Java应用

本次实战的目标是让Java应用支持docker的容器健康检查功能,接下来一起创建这个Java应用:

  1. 这是个基于maven构建的springboot工程,pom.xml内容如下:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>springboot-app-docker-health-check</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-app-docker-health-check</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>


            <!--使用jib插件-->
            <plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>jib-maven-plugin</artifactId>
                <version>1.7.0</version>
                <configuration>
                    <!--from节点用来设置镜像的基础镜像,相当于Docerkfile中的FROM关键字-->
                    <from>
                        <!--基础镜像是bolingcavalry/jdk8-healthcheck:0.0.1,该镜像已配置了健康检查参数-->
                        <image>bolingcavalry/jdk8-healthcheck:0.0.1</image>
                    </from>
                    <to>
                        <!--镜像名称和tag,使用了mvn内置变量${project.version},表示当前工程的version-->
                        <image>bolingcavalry/${project.artifactId}:${project.version}</image>
                    </to>
                    <!--容器相关的属性-->
                    <container>
                        <!--jvm内存参数-->
                        <jvmFlags>
                            <jvmFlag>-Xms1g</jvmFlag>
                            <jvmFlag>-Xmx1g</jvmFlag>
                        </jvmFlags>
                        <!--要暴露的端口-->
                        <ports>
                            <port>8080</port>
                        </ports>
                        <!--使用该参数将镜像的创建时间与系统时间对其-->
                        <useCurrentTimestamp>true</useCurrentTimestamp>
                    </container>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

上述pom.xml有以下几处需要注意:
a. 使用jib插件来将当前工程构建成docker镜像;
b. 基础镜像是前面构建的bolingcavalry/jdk8-healthcheck:0.0.1,以此为基础镜像的镜像都带有健康检查功能;

  1. 主要功能类是SpringbootAppDockerHealthCheckApplication.java
package com.bolingcavalry.springbootappdockerhealthcheck;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.List;

@SpringBootApplication
@RestController
@Slf4j
public class SpringbootAppDockerHealthCheckApplication {

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

    /**
     * 读取本地文本文件的内容并返回
     * @return
     */
    private String getLocalFileContent() {
        String content = null;

        try{
            InputStream is = new FileInputStream("/app/depend/abc.txt");
            List<String> lines = IOUtils.readLines(is, "UTF-8");

            if(null!=lines && lines.size()>0){
                content = lines.get(0);
            }
        } catch (FileNotFoundException e) {
            log.error("local file not found", e);
        } catch (IOException e) {
            log.error("io exception", e);
        }

        return content;
    }

    /**
     * 对外提供的http服务,读取本地的txt文件将内容返回,
     * 如果读取不到内容返回码为403
     * @return
     */
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public ResponseEntity<String> hello(){
        String localFileContent = getLocalFileContent();

        if(StringUtils.isEmpty(localFileContent)) {
            log.error("hello service error");
            return ResponseEntity.status(403).build();
        } else {
            log.info("hello service success");
            return ResponseEntity.status(200).body(localFileContent);
        }
    }

    /**
     * 该http服务返回当前应用是否正常,
     * 如果能从本地txt文件成功读取内容,当前应用就算正常,返回码为200,
     * 如果无法从本地txt文件成功读取内容,当前应用就算异常,返回码为403
     * @return
     */
    @RequestMapping(value = "/getstate", method = RequestMethod.GET)
    public ResponseEntity<String> getstate(){
        String localFileContent = getLocalFileContent();

        if(StringUtils.isEmpty(localFileContent)) {
            log.error("service is unhealthy");
            return ResponseEntity.status(403).build();
        } else {
            log.info("service is healthy");
            return ResponseEntity.status(200).build();
        }
    }
}

上述代码有以下几处需要注意:
a. hello方法是此应用对外提供的服务,如果本地文件abc.txt存在且内容不为空,hello方法的返回码就是200,否则返回码为403,表示当前服务出现异常;
b. getstate方法是新增的服务,该接口会被docke-daemon调用,如果返回码是200,就表示容器健康,如果返回码是403,表示容器不健康;
3. 在pom.xml文件所在目录执行mvn clean compile -U -DskipTests jib:dockerBuild,即可将当前工程构建为镜像,名为bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT
4. 至此,支持容器健康检查的Java应用镜像构建成功,接下来验证容器的健康检查功能是否正常;

验证步骤

验证的步骤如下:
a. 让应用容器正常工作,确保文件/app/depend/abc.txt是正常的,此时容器状态应该是healthy
b. 将文件/app/depend/abc.txt删除,此时应用hello接口返回码为403,并且容器状态变为unhealthy

验证操作

  1. Create a file abc.txt , the full path is /Users/zhaoqin/temp/201910/20/abc.txt , document content is a string, for example: 123456
  2. Execute the following command to create a new container with a java application image, the container will test folder mapped to the container / app / depend folder:
docker run --rm \
--name=java-health-check \
-p 8080:8080 \
-v /Users/zhaoqin/temp/201910/20:/app/depend \
bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT
  1. Console output less visible, indicating that the interface has been called health check:
2019-10-20 14:16:34.875  INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-10-20 14:16:34.876  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-10-20 14:16:34.892  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 16 ms
2019-10-20 14:16:34.959  INFO 1 --- [nio-8080-exec-1] pringbootAppDockerHealthCheckApplication : service is healthy
2019-10-20 14:16:40.159  INFO 1 --- [nio-8080-exec-2] pringbootAppDockerHealthCheckApplication : service is healthy
2019-10-20 14:16:45.356  INFO 1 --- [nio-8080-exec-4] pringbootAppDockerHealthCheckApplication : service is healthy
2019-10-20 14:16:50.580  INFO 1 --- [nio-8080-exec-6] pringbootAppDockerHealthCheckApplication : service is healthy
  1. Run docker ps to view the status of the vessel, are already visible Healthy :
(base) zhaoqindeMBP:20 zhaoqin$ docker ps
CONTAINER ID        IMAGE                                                             COMMAND                  CREATED              STATUS                        PORTS                    NAMES
51572d2488fb        bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT   "java -Xms1g -Xmx1g …"   About a minute ago   Up About a minute (healthy)   0.0.0.0:8080->8080/tcp   java-health-check
  1. Delete on host /Users/zhaoqin/temp/201910/20/abc.txt , equivalent abc.txt files in the container is removed, the console is visible at this time health check found the interface file does not exist when it is called, has been return 403 error code:
019-10-20 14:22:37.490 ERROR 1 --- [nio-8080-exec-7] pringbootAppDockerHealthCheckApplication : service is unhealthy
  1. Health check after 10 consecutive interface is called, and then execute the command docker ps to view the status of the vessel, has been seen Unhealthy :
(base) zhaoqindeMBP:20 zhaoqin$ docker ps
CONTAINER ID        IMAGE                                                             COMMAND                  CREATED             STATUS                     PORTS                    NAMES
51572d2488fb        bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT   "java -Xms1g -Xmx1g …"   7 minutes ago       Up 7 minutes (unhealthy)   0.0.0.0:8080->8080/tcp   java-health-check

At this point, Java applications in real Configuration container docker environment health check is complete, when you want to add a health check to their application, this article will give you some reference.

Published 328 original articles · won praise 946 · Views 1.17 million +

Guess you like

Origin blog.csdn.net/boling_cavalry/article/details/102649435