Docker容器中Spring Boot应用启动后立即关闭问题求助
Kotlin Spring Boot应用Docker启动后立刻关闭的解决方案
问题背景
本地运行正常的Kotlin Spring Boot应用,部署到Docker容器后启动即关闭,无错误日志。容器日志显示应用已成功启动,但进程随即退出。
可能原因&对应解决办法
1. 应用非Web类型,启动后无阻塞逻辑
如果你的Bot/后台应用没有引入Web依赖,Spring Boot启动完成后主线程会直接结束,导致容器关闭。
解决:
给应用添加阻塞逻辑,让主线程保持运行。两种方式:
- 直接在main方法中阻塞:
@SpringBootApplication class TwitchbotApplication fun main(args: Array<String>) { val context = runApplication<TwitchbotApplication>(*args) Thread.currentThread().join() }
- 用Spring的CountDownLatch优雅阻塞:
@SpringBootApplication class TwitchbotApplication { @Bean fun shutdownLatch() = CountDownLatch(1) @Bean fun keepAliveRunner(latch: CountDownLatch): CommandLineRunner { return CommandLineRunner { latch.await() } } } fun main(args: Array<String>) { runApplication<TwitchbotApplication>(*args) }
2. 自定义fatJar打包存在隐患
手动实现的fatJar可能遗漏依赖或存在类冲突,不如Spring Boot官方插件可靠。
解决:
改用Spring Boot官方bootJar插件打包:
修改build.gradle:
plugins { id 'org.springframework.boot' version '3.2.2' id 'io.spring.dependency-management' version '1.1.4' id 'org.jetbrains.kotlin.jvm' version '1.9.21' } // 移除自定义的fatJar任务,配置bootJar指定主类 tasks.named('bootJar') { mainClass = 'com.example.twitchbot.TwitchbotApplicationKt' } dependencies { // 确保必要依赖,比如web(如果是Web应用) implementation 'org.springframework.boot:spring-boot-starter-web' // 其他业务依赖... }
打包命令替换为:
./gradlew bootJar
Dockerfile无需修改COPY逻辑,因为bootJar生成的jar在build/libs/下,匹配*.jar即可。
3. 遗漏Web依赖(如果是Web应用)
如果你的应用是Web服务,但没引入spring-boot-starter-web,Spring Boot不会启动Tomcat等容器,启动后直接退出。
解决:
在build.gradle的dependencies块添加:
implementation 'org.springframework.boot:spring-boot-starter-web'
4. Docker配置细节检查
确保docker-compose中没有错误配置,添加restart: unless-stopped保证异常重启:
version: '3.8' services: twitchbot: image: [IMAGE-NAME] container_name: twitchbot restart: unless-stopped # 按需挂载配置文件 # volumes: # - ./application.yml:/app/application.yml
验证步骤
- 重新打包应用:
./gradlew bootJar - 重新构建镜像:
docker build --build-arg JAR_FILE=build/libs/*.jar -t [IMAGE-NAME] . - 启动容器:
docker-compose up -d - 查看日志:
docker logs -f twitchbot
内容的提问来源于stack exchange,提问作者PioPio
相关产品推荐
相关产品推荐

