IDEA中debug docker

2020-03-03  本文已影响0人  lsyarn

本文参考springboot docker 官网教程搭建了gs-spring-boot-docker项目(基于maven),然后在idea中进行配置,使项目能debug docker中运行的程序。

  1. 搭建项目工程

    按照springboot docker 官网教程在IDEA中构建好项目。

    hello.Application中添加一个资源/health作为服务健康检查路径

     @SpringBootApplication
     @RestController
     public class Application {
    
         @RequestMapping("/")
         public String home() {
             return "Hello Docker World";
         }
    
         @RequestMapping("/health")
         public int health() {
             return 0;
         }
    
         public static void main(String[] args) {
             SpringApplication.run(Application.class, args);
         }
    
     }
    
  2. 修改dockerfile添加healthcheck

    添加第二行和最后一行进行健康检查,健康检查的目的是让docker中的程序启动后再运行debug,防止debug启动失败

     FROM openjdk:8-jdk-alpine
     RUN apk add curl
     RUN addgroup -S spring && adduser -S spring -G spring
     USER spring:spring
     ARG DEPENDENCY=target/dependency
     COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib
     COPY ${DEPENDENCY}/META-INF /app/META-INF
     COPY ${DEPENDENCY}/BOOT-INF/classes /app
     ENTRYPOINT ["java","-cp","app:app/lib/*","hello.Application"]
     HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1
    
  3. 创建解压fat jar脚本

    这里创建一个shell脚本unpack_jar.sh,完成springboot docker 官网教程fat jar的解压。脚本内容如下,放到工程根目录:

    mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar)
    
  4. 添加IDEA配置(Edit Configurations)

    a. 添加maven clean和package配置

    分别添加名为gs-spring-boot-docker [clean]gs-spring-boot-docker [package]两个maven配置,完成清理和打包工作。

    b. 添加shell script

    添加shell script指向unpack_jar.sh文件,并且配置启动前依次运行gs-spring-boot-docker [clean]gs-spring-boot-docker [package],命名为build_app

    运行该shell script配置时,会先清理再打包项目,然后解压fat jar。

    c. 添加docker配置

    添加docker配置,使用dockerfile,选择项目的Dockerfile,然后完成端口绑定8080,完成环境变量配置JAVA_TOOL_OPTIONS=-agentlib:jdwp=transport=dt_socket,address=5005,server=y,suspend=n,命名为gs-spring-boot-docker

    这里需要说明,只需要绑定8080端口即可,用户debug的端口会在后面的配置中添加。JAVA_TOOL_OPTIONS环境变量的值需要和后面配置中生成的一直。

    e. 添加远程调试配置(remote)

    添加remote配置,并且配置启动前Launch Docker before debug选择之前添加的docker配置gs-spring-boot-docker,命名为debug-in-docker

    这里会默认将debug用的端口映射附加到docker的启动命令,所以前面的docker配置只需要设置app访问端口就行了。

    这里会根据你的配置参数生成Comand line arguments for remote JVM,我们把这个值赋给前面docker配置中的环境变量JAVA_TOOL_OPTIONS

  1. 进行debug

    先运行shell script配置build_app进行项目打包的fat jar的解压。

    再运行远程调试配置debug-in-docker,在一阵等待后(healthcheck需要等待)就可以看到debug-in-docker的Console页面输出Connected to the target VM, address: 'localhost:5005', transport: 'socket',表示应可以开始调试了。

    不知道为什么,不能将build_app添加到debug-in-docker中的运行前启动,需要手动依次点击build_appdebug-in-docker才能完成新版本打包->debug。

上一篇下一篇

猜你喜欢

热点阅读