Dockerfile - 基于 SpringBoot 项目自定义镜像(项目上线全过程)

 

目录

一、Dockerfile 自定义项目镜像

1.1、创建 SpringBoot 项目并编写

1.2、打包项目(jar)

1.3、编写 Dockerfile 文件,构建镜像

1.4、运行镜像并测试


一、Dockerfile 自定义项目镜像


1.1、创建 SpringBoot 项目并编写

a)简介:就是一个对 用户表 简单的增删改查的 SpringBoot 项目.

b)接口:采用 restful 风格

这里简单回顾以下 restful 风格接口规范

  • 原则: GET(查询)、POST(添加)、PUT(全字段更新)、PATCH(部分字段更新)、DELETE(删除)
  • 使用复数名词: user -> users、 car -> cars
  • 请求和响应指定: request: @RequestBody; response: @ResponseBody
  • 资源唯一标识需要通过路径传参,例如 id
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PutMapping("id")public String updateUser(@PathVariable("id") Integer id, @RequestBody User user) {user.setId(id);userService.update(user);return "ok";}@GetMapping("/{id}")public User getUser(@PathVariable("id") Integer id) {return userService.queryById(id);}@PostMappingpublic String addUser(@RequestBody User user) {userService.insert(user);return "ok";}@DeleteMapping("/{id}")public String delUser(@PathVariable("id") Integer id) {userService.deleteById(id);return "ok";}@GetMappingpublic List<User> getUserList() {return userService.queryAll();}}

c)配置文件:我们重点关注 服务器端口号 和 mysql 连接 ip 地址

server:port: 8081spring:datasource:url: jdbc:mysql://mysql:3306/demo?characterEncoding=utf8&useSSL=falseusername: rootpassword: 1111driver-class-name: com.mysql.cj.jdbc.Driver# 时间处理jackson:date-format: yyyy-MM-ddtime-zone: GMT+8# mybatis xml save path
mybatis:mapper-locations: classpath:mapper/*Mapper.xmlconfiguration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Ps:由于将来会将 springboot 项目和 mysql 配置到同一个自定义的 docker 网络下,因此 mysql 的 url 配置中的 ip 就使用容器名称即可.

1.2、打包项目(jar)

a)打包完毕后,根据以下目录找到包地址

或者在 target 的目录下也能看到

b)在云服务器上创建一个工作目录,用来存放 jar包 和 Dockerfile文件,将 jar 包从主机移到远端服务器.

[root@VM-8-17-centos apps]# ls
ssm-docker-0.0.1-SNAPSHOT.jar
[root@VM-8-17-centos apps]# pwd
/root/cyk/apps
[root@VM-8-17-centos apps]# 

1.3、编写 Dockerfile 文件,构建镜像

a)选取 openjdk1.8 镜像作为根基(open 表示开源的意思)

在 dockerhub 官网搜索 openjdk,找到对应的版本

找到 8-jdk

可以看到有下载命令,将 openjdk:8-jdk 写到 FROM 后面,表示以此镜像为基础进行开发.

b)编写 Dockerfile 文件

FROM openjdk:8-jdk
ENV BASE_PATH=/cyk/apps
WORKDIR $BASE_PATH
# 将宿主机上的 ssm-docker-0.0.1-SNAPSHOT.jar 移动到 /cyk/apps 目录下并改名为 apps.jar
ADD ssm-docker-0.0.1-SNAPSHOT.jar $BASE_PATH/apps.jar
EXPOSE 8081
ENTRYPOINT ["java", "-jar"]
CMD ["apps.jar"]

c)将 Dockerfile 文件移动到云服务器的工作目录( /cyk/apps )

[root@VM-8-17-centos apps]# rz -E
rz waiting to receive.
[root@VM-8-17-centos apps]# ls
Dockerfile  ssm-docker-0.0.1-SNAPSHOT.jar
[root@VM-8-17-centos apps]# pwd
/root/cyk/apps
[root@VM-8-17-centos apps]# 

d)构建镜像

[root@VM-8-17-centos apps]# docker build -t app:1.0 .
[+] Building 46.7s (8/8) FINISHED                                                                                     docker:default=> [internal] load build definition from Dockerfile                                                                            0.0s=> => transferring dockerfile: 326B                                                                                            0.0s=> [internal] load .dockerignore                                                                                               0.0s=> => transferring context: 2B                                                                                                 0.0s=> [internal] load metadata for docker.io/library/openjdk:8-jdk                                                               16.2s=> [1/3] FROM docker.io/library/openjdk:8-jdk@sha256:8a9d5c43f540e8d0c003c723a2c8bd20ae350a2efed6fb5719cae33b026f8e7c         30.0s=> => resolve docker.io/library/openjdk:8-jdk@sha256:8a9d5c43f540e8d0c003c723a2c8bd20ae350a2efed6fb5719cae33b026f8e7c          0.0s=> => sha256:e24ac15e052e04a3462ef4984b5d83214f7f65c06f54acd3745a1926e226be16 7.81kB / 7.81kB                                  0.0s=> => sha256:9b829c73b52b92b97d5c07a54fb0f3e921995a296c714b53a32ae67d19231fcd 5.15MB / 5.15MB                                  0.9s=> => sha256:cb5b7ae361722f070eca53f35823ed21baa85d61d5d95cd5a95ab53d740cdd56 10.87MB / 10.87MB                                0.7s=> => sha256:8a9d5c43f540e8d0c003c723a2c8bd20ae350a2efed6fb5719cae33b026f8e7c 1.29kB / 1.29kB                                  0.0s=> => sha256:9413213335131c4e06b21a8e379bd9b6a20afcd6b762540463d5f7c72942dcdd 1.79kB / 1.79kB                                  0.0s=> => sha256:0e29546d541cdbd309281d21a73a9d1db78665c1b95b74f32b009e0b77a6e1e3 54.92MB / 54.92MB                               18.6s=> => sha256:6494e4811622b31c027ccac322ca463937fd805f569a93e6f15c01aade718793 54.57MB / 54.57MB                               21.5s=> => sha256:668f6fcc5fa5532a1dd793456f64daf954192e0521fd65d42af584d5e2d93f55 5.42MB / 5.42MB                                  1.3s=> => sha256:c0879393b07ef5fa816c292b00e3eb4945890bc2a69ab0d1754240cbe9cedf21 212B / 212B                                      1.6s=> => sha256:bef50c41a74d450f2d708be5971c3ba635ed1a714af7f4fa1497886adb2fa734 106.00MB / 106.00MB                             12.4s=> => extracting sha256:0e29546d541cdbd309281d21a73a9d1db78665c1b95b74f32b009e0b77a6e1e3                                       3.1s=> => extracting sha256:9b829c73b52b92b97d5c07a54fb0f3e921995a296c714b53a32ae67d19231fcd                                       0.3s=> => extracting sha256:cb5b7ae361722f070eca53f35823ed21baa85d61d5d95cd5a95ab53d740cdd56                                       0.3s=> => extracting sha256:6494e4811622b31c027ccac322ca463937fd805f569a93e6f15c01aade718793                                       3.2s=> => extracting sha256:668f6fcc5fa5532a1dd793456f64daf954192e0521fd65d42af584d5e2d93f55                                       0.2s=> => extracting sha256:c0879393b07ef5fa816c292b00e3eb4945890bc2a69ab0d1754240cbe9cedf21                                       0.0s=> => extracting sha256:bef50c41a74d450f2d708be5971c3ba635ed1a714af7f4fa1497886adb2fa734                                       3.3s=> [internal] load build context                                                                                               0.1s=> => transferring context: 9.88kB                                                                                             0.0s=> [2/3] WORKDIR /cyk/apps                                                                                                     0.2s=> [3/3] ADD ssm-docker-0.0.1-SNAPSHOT.jar /cyk/apps/apps.jar                                                                  0.1s=> exporting to image                                                                                                          0.1s=> => exporting layers                                                                                                         0.1s=> => writing image sha256:89839bc7dd0c546892b523403eb18d8b3a5d84993c4be71a9dd4ca2875bd1e9d                                    0.0s=> => naming to docker.io/library/app:1.0                                                                                      0.0s
[root@VM-8-17-centos apps]# docker images
REPOSITORY                  TAG              IMAGE ID       CREATED          SIZE
app                         1.0              89839bc7dd0c   28 seconds ago   526MB

1.4、运行镜像并测试

a)先自定义一个网桥,方便后续运行容器时直接加入到统一网络下.

[root@VM-8-17-centos apps]# docker network create mynet
dd8d11bdbd1ff64905a877c350752521f8dc772480b0a9db378769d283a143ac
[root@VM-8-17-centos apps]# 
[root@VM-8-17-centos apps]# 
[root@VM-8-17-centos apps]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
f84ca6fc4b48   bridge    bridge    local
a1b8a8a8e372   host      host      local
dd8d11bdbd1f   mynet     bridge    local
38b4ab15453c   none      null      local

d)启动容器

启动 mysql:

docker run -d --name mysql -p 3306:3306 -v mysql-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=1111 --network mynet mysql:5.7

Ps:这里不要忘了准备 MySQL 的数据 

启动 springboot 项目:

docker run -d --name app -p 8081:8081 --network mynet app:1.0

检查启动日志:

[root@VM-8-17-centos apps]# docker logs -f app.   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::                (v2.7.6)2023-12-28 10:40:00.259  INFO 1 --- [           main] com.cyk.SsmDockerApplication             : Starting SsmDockerApplication using Java 1.8.0_312 on 4ecafb679d7f with PID 1 (/apps/apps.jar started by root in /apps)
2023-12-28 10:40:00.273  INFO 1 --- [           main] com.cyk.SsmDockerApplication             : No active profile set, falling back to 1 default profile: "default"
2023-12-28 10:40:02.271  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2023-12-28 10:40:02.290  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-12-28 10:40:02.290  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.69]
2023-12-28 10:40:02.391  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-12-28 10:40:02.391  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1959 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Parsed mapper file: 'class path resource [mapper/UserMapper.xml]'
2023-12-28 10:40:03.399  INFO 1 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2023-12-28 10:40:03.675  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2023-12-28 10:40:03.690  INFO 1 --- [           main] com.cyk.SsmDockerApplication             : Started SsmDockerApplication in 4.412 seconds (JVM running for 5.138)

 

e)注意事项:运行容器时,一旦出现以下情况

no main manifest attribute, in apps.jar

一定要看一下 pom.xml 文件中是否存在 <skip>true<skip> 的配置,因为打包时他会跳过主类.

f)postman 测试接口

这里我为了防止黑客攻击,建立隧道和远端服务器连接,开放映射本地 9091 端口.

访问后,云服务器上检查日志,也可以观察到打印相应日志(测试成功)

[root@VM-8-17-centos ~]# docker logs app.   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::                (v2.7.6)2023-12-28 10:40:00.259  INFO 1 --- [           main] com.cyk.SsmDockerApplication             : Starting SsmDockerApplication using Java 1.8.0_312 on 4ecafb679d7f with PID 1 (/apps/apps.jar started by root in /apps)
2023-12-28 10:40:00.273  INFO 1 --- [           main] com.cyk.SsmDockerApplication             : No active profile set, falling back to 1 default profile: "default"
2023-12-28 10:40:02.271  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2023-12-28 10:40:02.290  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-12-28 10:40:02.290  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.69]
2023-12-28 10:40:02.391  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-12-28 10:40:02.391  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1959 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Parsed mapper file: 'class path resource [mapper/UserMapper.xml]'
2023-12-28 10:40:03.399  INFO 1 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2023-12-28 10:40:03.675  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2023-12-28 10:40:03.690  INFO 1 --- [           main] com.cyk.SsmDockerApplication             : Started SsmDockerApplication in 4.412 seconds (JVM running for 5.138)
2023-12-28 10:43:17.431  INFO 1 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-12-28 10:43:17.431  INFO 1 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-12-28 10:43:17.432  INFO 1 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@45f8529a] was not registered for synchronization because synchronization is not active
2023-12-28 10:43:17.524  INFO 1 --- [nio-8081-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-12-28 10:43:17.819  INFO 1 --- [nio-8081-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1585874780 wrapping com.mysql.cj.jdbc.ConnectionImpl@1380045] will not be managed by Spring
==>  Preparing: select * from user;
==> Parameters: 
<==    Columns: id, name, age
<==        Row: 1, cyk, 20
<==        Row: 2, lyj, 19
<==        Row: 4, pdder, 100
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@45f8529a]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/307412.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于Java车间工时管理系统(源码+部署文档)

博主介绍&#xff1a; ✌至今服务客户已经1000、专注于Java技术领域、项目定制、技术答疑、开发工具、毕业项目实战 ✌ &#x1f345; 文末获取源码联系 &#x1f345; &#x1f447;&#x1f3fb; 精彩专栏 推荐订阅 &#x1f447;&#x1f3fb; 不然下次找不到 Java项目精品实…

论文润色改善附录内容质量

大家好&#xff0c;今天来聊聊论文润色改善附录内容质量&#xff0c;希望能给大家提供一点参考。 以下是针对论文重复率高的情况&#xff0c;提供一些修改建议和技巧&#xff0c;可以借助此类工具&#xff1a; 标题&#xff1a;论文润色改善附录内容质量――提升论文的完整性与…

OpenCV-Python(30):Harris角点检测

目标 理解Harris角点检测的概念掌握函数cv2.cornerHarris()、cv2.cornerSubPix()的用法 Harris算法原理 通过前面的图像特征介绍&#xff0c;我们知知道了角点的一个特性&#xff1a;向任何方向移动变化都很大。Chris_Harris 和Mike_Stephens 在1988 年的文章《A Combined Co…

直流电机驱动开发笔记

直流电机总体来说应用非常广泛&#xff0c;最近项目需要直流电机&#xff0c;本想着应该是很简单的事情&#xff0c;结果也搞了好久&#xff0c;今天算是可以阶段性总结下。也不知道怎么总结好。就拿碰到问题记录下。前提&#xff1a;本人一直是软件开发&#xff0c;对这个之前…

【盘点】再见2023年,年度总结

文章目录 &#x1f50a;博主介绍&#x1f964;本文内容事业AI大模型交互式问答图文视频生成功能型应用生成 行情危机感 爱情情绪价值会撩沟通 生理价值颜值相貌、身材体态、审美穿搭关于男性与女性间的那份本能需求生育 物质价值 &#x1f4e2;文章总结&#x1f4e5;博主目标 &…

使用ffmpeg调整视频分辨率/帧率并保持高清晰度

1 原始视频信息 通过ffmpeg -i命令查看视频基本信息 ffmpeg -i input.mp4 ffmpeg version 6.1-essentials_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developersbuilt with gcc 12.2.0 (Rev10, Built by MSYS2 project)configuration: --enable-gpl --enable-ve…

众和策略:人工智能风起云涌 算力基建支撑加速前进

2023年&#xff0c;人工智能技术完结质的飞跃。通过生成式AI&#xff08;AIGC&#xff09;技术&#xff0c;人们可用自然语言与机器进行便捷交互&#xff0c;并将海量的数据通过训练、推理&#xff0c;快速转化为出产力&#xff0c;发生实践商业价值。 AI技术加快向各行各业渗…

【iptables】修改规则和保存规则

1 修改规则 &#xff08;1&#xff09;修改指定表中指定链的规则 iptables -t 表名 -R 链名 规则序号 -s 源地址 -j 处理动作 接着上面的例子&#xff0c;假如我们想把下面的规则中的动作从DROP改为ACCEPT 可以使用-R选项来修改指定的链中的规则&#xff0c;在修改规则时指定规…

GA/T1400公安视图库在视频监控系统中对接及方案

公安视频图像信息应用系统系列标准&#xff0c;标号为GA/T 1400&#xff0c;现行版本为2017年版&#xff0c;由公安部发布。现较广泛地使用于平安城市安防监控系统、智慧城市安防监控系统、雪亮工程安防监控系统之中。 公安视频图像信息应用系统系列标准&#xff0c;共分为4个部…

web三层架构

目录 1.什么是三层架构 2.运用三层架构的目的 2.1规范代码 2.2解耦 2.3代码的复用和劳动成本的减少 3.各个层次的任务 3.1web层&#xff08;表现层) 3.2service 层(业务逻辑层) 3.3dao 持久层(数据访问层) 4.结合mybatis简单实例演示 1.什么是三层架构 三层架构就是把…

echarts半圆进度条半圆饼图

drawmonthproduce(){this.monthproduce echarts.init(document.getElementById(monthproduce));var data 60; //数值大小var max 100; //满刻度大小this.monthproduce.setOption({title: [{text: data %, left: 50%,top: 70%,textAlign: center,textStyle: {// fontWeight…

【neo4j】desktop下载

【neo4j】desktop下载 https://neo4j.com/download/ 点击download&#xff0c;填写表格 之后就可以正常使用了