手把手教你为 Spring Boot 应用制作 Docker 镜像,并实现配置文件外置_springboot docker镜像
在当今微服务架构盛行的时代,Spring Boot 凭借其快速开发、便捷部署的特性,成为了 Java 开发者构建后端服务的首选框架。而 Docker 作为容器化技术的佼佼者,能够实现应用程序及其依赖项的打包和隔离,极大地提升了应用部署的效率和一致性。本文将详细介绍如何为 Spring Boot 应用制作 Docker 镜像,并实现配置文件外置,让你的应用部署更加灵活高效。
一、准备工作
在开始制作 Docker 镜像和外置配置文件之前,确保你已经完成以下准备工作(不具体展开赘述,默认大家已具备):
- 安装 JDK:Spring Boot 应用需要 Java 运行环境,确保你的开发环境中已安装合适版本的 JDK(推荐 JDK 8 及以上)。
- 安装 Maven 或 Gradle:用于构建 Spring Boot 项目,根据项目使用的构建工具进行安装。
- 安装 Docker:前往 Docker 官方网站(https://www.docker.com/ ),根据你的操作系统下载并安装 Docker Desktop 或 Docker Engine。
二、创建 Spring Boot 项目并指定配置文件(比较简单,如果想要完整项目请评论区留言)
1.关键代码:
@EnableScheduling@SpringBootApplication@PropertySource(\"file:./application.properties\")public class ProjectApplication {public static void main(String[] args) {SpringApplication.run(ProjectApplication.class, args);}}
@PropertySource(\"file:./application.properties\")把外部配置文件加载到 Spring 的环境当中。
2、请求验证接口Controller层,非常简单不在赘述
@RestControllerpublic class UserController {@GetMapping(\"/send/{cmd}\")public String SendCmd(@PathVariable String cmd) {return cmd;}}
2、配置文件:
server.port = 8082spring.application.name=springbootspring.main.allow-bean-definition-overriding=true
3、将文件上传至Linux目录下(作者用的centos7)
[root@localhost fileConfig]# ll总用量 52612-rw-r--r--. 1 root root 104 5月 16 17:53 application.properties-rw-r--r--. 1 root root 53867587 5月 16 17:53 springboot-0.0.1.jar
三、编写 Dockerfile文件
1.创建名为Dockerfile的文件,内容如下:
FROM openjdk:8-jdk-alpineRUN mkdir -p /appPathWORKDIR /appPathARG JAR_FILE=springboot-0.0.1.jarCOPY ${JAR_FILE} app.jarEXPOSE 8082ENV TZ=Asia/Shanghai JAVA_OPTS=\"-Xms128m -Xmx256m -Djava.security.egd=file:/dev/./urandom\"CMD sleep 30; java -jar app.jar $JAVA_OPTS
2.放入同目录下
[root@localhost fileConfig]# ll总用量 52616-rw-r--r--. 1 root root 104 5月 16 17:53 application.properties-rw-r--r--. 1 root root 277 5月 16 18:27 Dockerfile-rw-r--r--. 1 root root 53867587 5月 16 17:53 springboot-0.0.1.jar
四、打docker镜像
1.打镜像
[root@localhost fileConfig]# docker build -t demo:0.1 .[+] Building 6.0s (9/9) FINISHED docker:default => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 375B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/openjdk:8-jdk-alpine 0.7s => [internal] load build context 4.2s => => transferring context: 53.88MB 4.1s => CACHED [1/4] FROM docker.io/library/openjdk:8-jdk-alpine@sha256:94792824df2df33402f201713f932b58cb9de94a0cd524164a0f2283343547b3 0.0s => [2/4] RUN mkdir -p /appPath 3.8s => [3/4] WORKDIR /appPath 0.2s => [4/4] COPY springboot-0.0.1.jar app.jar0.3s => exporting to image 0.7s => => exporting layers 0.7s => => writing image sha256:aa7ed06093ce92c4a96473a1bd4ad00a00ef9b7477e2d1bd3a0fbc2807bcb71e 0.0s => => naming to docker.io/library/demo:0.10.0s
2.查看打好的镜像
[root@localhost fileConfig]# docker images|grep demodemo 0.1 aa7ed06093ce 3 minutes ago 159MB
五、启动容器
1、启动容器
[root@localhost fileConfig]# docker run -d -v $(pwd)/application.properties:/appPath/application.properties -p 8082:8082 --name demo01 demo:0.1b84e11a89dabf01aa0b987af12bd6284b5c56967250b33c05935fae93f386b9d
2、查看日志
[root@localhost fileConfig]# docker logs -f demo01 . ____ _ __ _ _ /\\\\ / ___\'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\( ( )\\___ | \'_ | \'_| | \'_ \\/ _` | \\ \\ \\ \\ \\\\/ ___)| |_)| | | | | || (_| | ) ) ) ) \' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.14.RELEASE)2025-05-16 18:44:34.937 INFO 1 --- [ main] com.kangwei.ProjectApplication : Starting ProjectApplication v0.0.1 on b84e11a89dab with PID 1 (/appPath/app.jar started by root in /appPath)2025-05-16 18:44:34.984 INFO 1 --- [ main] com.kangwei.ProjectApplication : No active profile set, falling back to default profiles: default2025-05-16 18:44:43.029 INFO 1 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named \'errorChannel\' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.2025-05-16 18:44:43.122 INFO 1 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named \'integrationHeaderChannelRegistry\' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.2025-05-16 18:44:43.931 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean \'org.springframework.integration.config.IntegrationManagementConfiguration\' of type [org.springframework.integration.config.IntegrationManagementConfiguration$$EnhancerBySpringCGLIB$$f4cbbf60] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2025-05-16 18:44:44.078 INFO 1 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean \'integrationDisposableAutoCreatedBeans\' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2025-05-16 18:44:46.491 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8082 (http)2025-05-16 18:44:46.661 INFO 1 --- [ main] o.a.coyote.http11.Http11NioProtocol : Initializing ProtocolHandler [\"http-nio-8082\"]2025-05-16 18:44:46.809 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]2025-05-16 18:44:46.810 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.34]2025-05-16 18:44:47.608 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2025-05-16 18:44:47.615 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 12132 ms2025-05-16 18:44:50.518 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService \'applicationTaskExecutor\'2025-05-16 18:44:52.186 INFO 1 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService \'taskScheduler\'2025-05-16 18:44:52.930 INFO 1 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the \'errorChannel\' channel2025-05-16 18:44:52.931 INFO 1 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel \'springboot.errorChannel\' has 1 subscriber(s).2025-05-16 18:44:52.931 INFO 1 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger2025-05-16 18:44:53.013 INFO 1 --- [ main] o.a.coyote.http11.Http11NioProtocol : Starting ProtocolHandler [\"http-nio-8082\"]2025-05-16 18:44:53.160 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path \'\'2025-05-16 18:44:53.168 INFO 1 --- [ main] com.kangwei.ProjectApplication : Started ProjectApplication in 24.336 seconds (JVM running for 27.486)
3、请求服务接口
[root@localhost fileConfig]# curl http://127.0.0.1:8082/send/123456789123456789[root@localhost fileConfig]#
八、总结
通过以上步骤,我们成功地为 Spring Boot 应用制作了 Docker 镜像,并实现了配置文件外置。这样不仅能够方便地在不同环境中部署应用,还能灵活地修改配置,而无需重新构建镜像。希望本文对你在 Spring Boot 应用的容器化部署和配置管理方面有所帮助。
上述步骤已涵盖制作镜像与外置配置文件的核心操作。若你在实践中遇到问题,或想了解更多优化技巧,欢迎交流。