注:本文是本人根据B站【狂神说Java】Docker视频所写,仅供学习参考。
SpringBoot微服务打包Docker镜像
1、构建springboot项目




等待项目构建完成!

# 创建Controller包 和 HelloController
package com.example.springbootdemo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "Hellp SpringBoot!";
}
}
# 启动服务
# 测试是否可以访问 http://localhost:8080/hello
# 成功 将其打包

2、打包应用

测试jar包是否可以运行
# 进入cmd命令 进入 jar 所在目录
java -jar springbootdemo-0.0.1-SNAPSHOT.jar
# 启动成功 说明jar包没有问题!

3、编写dockerfile
在IDEA编写Dockerfile 安装 docker 高亮插件
进入 settings 找到 Plugins 搜索 Docker 点击安装



# 创建Dockerfile 文件 编写 Dockerfile 内容
FROM java:8
COPY *.jar /app.jar
CMD ["--server.port=8080"]
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
4、构建镜像
# 在linux中创建 /data/docker/hello 文件夹
[root@localhost ~]# cd /data/docker
[root@localhost docker]# ls
mysql nginx redis tomcat
[root@localhost docker]# mkdir hello
[root@localhost docker]# ls
hello mysql nginx redis tomcat
[root@localhost docker]# cd hello/
[root@localhost hello]# ls
# 将jar包和Dockerfile拷贝到hello文件夹下
[root@localhost hello]# ls
Dockerfile springbootdemo-0.0.1-SNAPSHOT.jar
# 构建镜像
[root@localhost hello]# docker build -t springboothello:1.0 .
Sending build context to Docker daemon 16.97MB
Step 1/5 : FROM java:8
8: Pulling from library/java
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
60170fec2151: Pull complete
e98f73de8f0d: Pull complete
11f7af24ed9c: Pull complete
49e2d6393f32: Pull complete
bb9cdec9c7f3: Pull complete
Digest: sha256:c1ff613e8ba25833d2e1940da0940c3824f03f802c449f3d1815a66b7f8c0e9d
Status: Downloaded newer image for java:8
---> d23bdf5b1b1b
Step 2/5 : COPY *.jar /app.jar
---> 2cf09d1e85e1
Step 3/5 : CMD ["--server.port=8080"]
---> Running in e740fdad6a12
Removing intermediate container e740fdad6a12
---> b7421d6cb7a0
Step 4/5 : EXPOSE 8080
---> Running in fc2ba01c0dcb
Removing intermediate container fc2ba01c0dcb
---> f15e29bc7d62
Step 5/5 : ENTRYPOINT ["java","-jar","/app.jar"]
---> Running in 2472daf13fa3
Removing intermediate container 2472daf13fa3
---> 548357348291
Successfully built 548357348291
Successfully tagged springboothello:1.0
# 构建成功

5、发布运行
[root@localhost hello]# docker run -d --restart=always -p 8088:8080 --name hello springboothello:1.0
12ebdf58e8f6c739b7596ecd45d3c97fe9d101e4462a3a109fb9af3b12a11375
# 本地测试
[root@localhost hello]# curl localhost:8088
{"timestamp":"2020-11-15T03:28:02.319+00:00","status":404,"error":"Not Found","message":"","path":"/"}
[root@localhost hello]# curl localhost:8088/hello
Hellp SpringBoot!
# 成功

# 通过 http://ip:8088/hello
# 成功

本文介绍了如何将一个SpringBoot微服务应用打包成Docker镜像并进行运行。首先创建了一个简单的HelloController,然后打包应用确保其可运行。接着编写了Dockerfile,并在Linux环境中构建Docker镜像。最后,发布了镜像并成功通过http://ip:8088/hello访问应用。
5839

被折叠的 条评论
为什么被折叠?



