In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
In view of how the Java application configures container health check in the docker environment, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Today, add a health check to the container of the java application so that the status of the application can be monitored and viewed at any time.
Actual combat environment information
Operating system: macOS Catalina 10.15
Docker:19.03.2
Brief introduction of java Application
Today's practical java applications are used to simulate production environment applications with the following characteristics:
Ordinary springboot applications that provide http services to the outside world. Path: / hello
The springboot application runs in the docker container with a file named abc.txt in the container's / app/depend/ directory
When the above abc.txt file exists, the hello interface of the springboot application is normal. If the abc.txt does not exist, the springboot application does not provide services, which is equivalent to an unhealthy state (to simulate an exception in the application).
Source code download
If you do not want to write code, the source code of the above springboot application can be downloaded from GitHub The address and link information are shown in the following table: | name | Link | remarks | |:-- |:-- | Project home page | https://github.com/zq2599/blog_demos | GitHub home page of the project | | git warehouse address (https) | https://github.com/zq2599/blog_demos.git | the warehouse address of the project source code | Https protocol | | git warehouse address (ssh) | git@github.com:zq2599/blog_demos.git | the warehouse address of the project source code, ssh protocol |
There are multiple folders in this git project. The application of this chapter is under the springboot-app-docker-health-check folder, as shown in the red box below:
Introduction to the steps
The steps to apply the health check of the access container are as follows:
A basic image is required to make a java application into a docker image, so prepare the basic image first, and configure all the parameters of container health check in the basic image, including the API path that provides container health information, which is defined as / getstate here.
Transform the java application, provide / getstate interface service, and determine whether the current application is healthy according to the actual situation of the business. The return code is 200when healthy and 403when unhealthy.
Compile and build the application and generate a docker image
Validate
Create a basic image
Create a file named Dockerfile with the following contents:
# Docker file from bolingcavalry# VERSION 0.0.roomAuthor: FROM openjdk:8-jdk-stretch# author of bolingcavalry# basic image MAINTAINER BolingCavalry # Health check parameter setting: check every 5 seconds, and the API timeout is 2 seconds. If you return 1 for 10 times in a row, you can determine that the container is unhealthy HEALTHCHECK-interval=5s-timeout=2s-retries=10\ CMD curl-silent-fail localhost:8080/getstate | | exit 1
From the above visible Dockerfile content is very simple, select its own basic image as openjdk:8-jdk-stretch, and then configure the health check parameters: | Parameter name | function | |-|-| health-cmd | specify the command to be executed in the container to check the container's health status | | health-interval | the interval between each health check. The default is 30 seconds | | health-retries | assume that the value is 3. Indicates that if the returned result of three consecutive tests is unhealthy, the container is judged to be unhealthy. The default value is 3 | health-timeout | timeout. Default is 30 seconds | 2. Execute the command docker build-t bolingcavalry/jdk8-healthcheck:0.0.1 in the directory where the Dockerfile file is located. (do not leave out the last dot). The output of the console is as follows, indicating that the image has been built successfully:
(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.6kBStep 1 Already existsDigest 3: FROM openjdk:8-jdk-stretch8-jdk-stretch: Pulling from library/openjdk9a0b0ce99936: Already existsdb3b6004c61a: Already existsf8f075920295: Already exists6ef14aff1139: Already exists962785d3b7f9: Already exists631589572f9b: Already existsc55a0c6f4c7b: Already existsDigest: sha256:8bce852e5ccd41b17bf9704c0047f962f891bdde3e401678a52d14a628defa49Status: Downloaded newer image for openjdk:8-jdk-stretch-> 57c2c2d2643dStep 2 Already exists962785d3b7f9 3: MAINTAINER BolingCavalry-> Running in 270f78efa617Removing Intermediate container 270f78efa617-- > 01b5df83611dStep 3Accord 3: HEALTHCHECK-- interval=5s-- timeout=2s-- retries=10 CMD curl-- silent-fail localhost:8080/getstate | | exit 1-- > Running in 7cdd08b9ca22Removing intermediate container 7cdd08b9ca22-- > 9dd7ffb22df4Successfully built 9dd7ffb22df4Successfully tagged bolingcavalry/jdk8-healthcheck:0.0.1
At this time, there is already an image called bolingcavalry/jdk8-healthcheck:0.0.1 on the host, which has the parameter configuration of container health check. Other images built with this as the basic image integrate the features of health check.
If you have already registered on hub.docker.com, you can log in with the docker login command, and then execute the following command to push the local image to hub.docker.com for more people to use:
Docker push bolingcavalry/jdk8-healthcheck:0.0.1 revamping Java Application
The goal of this actual combat is to enable the Java application to support the container health check feature of docker, and then create this Java application:
This is a springboot project built on maven. The pom.xml content is as follows:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.0.RELEASE com.bolingcavalry springboot-app-docker-health-check 0.0.1-SNAPSHOT springboot-app-docker-health-check Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web Org.projectlombok lombok true commons-io commons-io 2.5 org.springframework.boot spring-boot-starter-test test org.junit.vintage Junit-vintage-engine org.springframework.boot spring-boot-maven-plugin com.google.cloud.tools jib-maven-plugin 1.7.0 bolingcavalry/jdk8-healthcheck:0.0.1 bolingcavalry/$ {project.artifactId} : ${project.version}-Xms1g-Xmx1g 8080 true
The above pom.xml has the following points to pay attention to: a. Use the jib plug-in to build the current project into a docker image; b. The basic image is the bolingcavalry/jdk8-healthcheck:0.0.1 built previously, and all the images based on it have health check function.
The main functional class is 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@Slf4jpublic class SpringbootAppDockerHealthCheckApplication {public static void main (String [] args) {SpringApplication.run (SpringbootAppDockerHealthCheckApplication.class, args);} / * reads the contents of the local text file and returns * @ return * / private String getLocalFileContent () {String content = null; try {InputStream is = new FileInputStream ("/ app/depend/abc.txt") List lines = IOUtils.readLines (is, "UTF-8"); if (nullified 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;} / * external http service. Read the local txt file and return the content. * if the content cannot be read, the return code is 403 * @ return * / @ RequestMapping (value = "/ hello", method = RequestMethod.GET) public ResponseEntity 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) }} / * * whether it is normal for the current application to be returned by the http service. * if the content can be successfully read from the local txt file, the current application is normal, with a return code of 200. if the content cannot be successfully read from the local txt file, the current application is considered an exception. The return code is 403 * @ return * / @ RequestMapping (value = "/ getstate", method = RequestMethod.GET) public ResponseEntity 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 ();}
The above code has the following points to note: A. the hello method is the service provided by this application. If the local file abc.txt exists and the content is not empty, the return code of the hello method is 200. otherwise, the return code is 403, indicating that the current service has an exception. B. the getstate method is a new service. The API will be called by docke-daemon. If the return code is 200, the container is healthy. If the return code is 403, the container is unhealthy. 3. Execute mvn clean compile-U-DskipTests jib:dockerBuild in the directory where the pom.xml file is located to build the current project as an image, named bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT 4. 0. So far, the Java application image supporting container health check has been successfully built. Next, verify whether the container health check function is normal.
Verification step
The steps of verification are as follows: a. Let the application container work properly and make sure that the file / app/depend/abc.txt is normal, and the container state should be healthy b. Delete the file / app/depend/abc.txt, and the return code of the hello API is 403, and the container status changes to unhealthy.
Verification operation
Create the file abc.txt, the full path is / Users/zhaoqin/temp/201910/20/abc.txt, and the content of the file is a string, for example: 123456
Execute the following command to create a container with the newly created java application image, which maps the test folder to the container's / app/depend folder:
Docker run-- rm\-- name=java-health-check\-- p 8080 Users/zhaoqin/temp/201910/20:/app/depend 8080\-v / Users/zhaoqin/temp/201910/20:/app/depend\ bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT
The following output can be seen in the console, indicating that the health check API has been called:
2019-10-20 14 INFO 16 INFO 34.875 INFO 1-[nio-8080-exec-1] o.a.c.c.C. [tomcat]. [localhost]. [/]: Initializing Spring DispatcherServlet 'dispatcherServlet'2019-10-20 14 Initializing Spring DispatcherServlet' INFO-10-20 14 Initializing Spring DispatcherServlet 34.876 Tomcat 1-[nio-8080-exec-1] o.s.web.servlet.DispatcherServlet: Initializing Servlet' dispatcherServlet'2019-10-20 14 14 14 1414 1634.892 tomcat 1-- -- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet: Completed initialization in 16 ms2019-10-20 14 ms2019 16 INFO 34.959 INFO 1-[nio-8080-exec-1] pringbootAppDockerHealthCheckApplication: service is healthy2019-10-20 14 Completed initialization in 16 ms2019 40.159 INFO 1-[nio-8080-exec-2] pringbootAppDockerHealthCheckApplication: service is healthy2019-10-20 14 Swiss 16V 45.356 INFO 1-- [nio-8080-exec-4] pringbootAppDockerHealthCheckApplication : service is healthy2019-10-20 14 nio-8080-exec-6 16 nio-8080-exec-6 50.580 INFO 1-[nio-8080-exec-6] pringbootAppDockerHealthCheckApplication: service is healthy
Execute the command docker ps to check the container status, and you can see that it is already healthy:
(base) zhaoqindeMBP:20 zhaoqin$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES51572d2488fb 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.0pur8080-> 8080/tcp java-health-check
Deleting the / Users/zhaoqin/temp/201910/20/abc.txt on the host is equivalent to deleting the abc.txt file in the container. The console can see that the health check API found that the file does not exist when it is called, and a 403 error code has been returned:
490 ERROR 1-[nio-8080-exec-7] pringbootAppDockerHealthCheckApplication: service is unhealthy
After the health check API has been called for 10 times in a row, execute the command docker ps to check the status of the container. You can see that it is already unhealthy:
(base) zhaoqindeMBP:20 zhaoqin$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES51572d2488fb bolingcavalry/springboot-app-docker-health-check:0.0.1-SNAPSHOT "java-Xms1g-Xmx1g..." 7 minutes ago Up 7 minutes (unhealthy) 0.0.0.0 unhealthy 80-> 8080/tcp java-health-check 's answer to the question about how Java applications configure container health check in docker environment is here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.