Docker体验(二) - 自建Image

时间:2022-07-25
本文章向大家介绍Docker体验(二) - 自建Image,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天尝试把Spring Boot放到Docker中启动。

制作Spring Boot程序

  • Spring Boot启动类
@RestController
@SpringBootApplication
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }
    @GetMapping("ping")
    public String ping() {
        return "Hello World From Spring In Docker";
    }
}
  • 生成启动Jar
mvn clean package
# 生成
helloworld-0.0.1-SNAPSHOT.jar
  • 编写Dockerfile
# 该 image 文件继承官方的 openjdk image,冒号表示标签,这里标签是8-jdk-alpine,即8-jdk-alpine版本的 openjdk
FROM openjdk:8-jdk-alpine
# 复制jar包围app.jar
COPY helloworld-0.0.1-SNAPSHOT.jar app.jar
# 入口命令
ENTRYPOINT ["java","-jar","/app.jar"]
  • 放到同一个目录helleworld
E:Workspacedockerhelloworld>dir
 驱动器 E 中的卷是 Document
 卷的序列号是 D42E-258E

 E:Workspacedockerhelloworld 的目录

2020/09/18  19:40    <DIR>          .
2020/09/18  19:40    <DIR>          ..
2020/09/18  19:42               108 Dockerfile
2020/09/18  19:35        18,339,476 helloworld-0.0.1-SNAPSHOT.jar
  • 制作镜像
E:Workspacedockerhelloworld>docker build -t tenmao/helloworld .
Sending build context to Docker daemon  18.34MB
Step 1/3 : FROM openjdk:8-jdk-alpine
8-jdk-alpine: Pulling from library/openjdk
e7c96db7181b: Pull complete                                                                                             f910a506b6cb: Pull complete                                                                                             c2274a1a0e27: Pull complete                                                                                             Digest: sha256:94792824df2df33402f201713f932b58cb9de94a0cd524164a0f2283343547b3
Status: Downloaded newer image for openjdk:8-jdk-alpine
 ---> a3562aa0b991
Step 2/3 : COPY helloworld-0.0.1-SNAPSHOT.jar app.jar
 ---> a93e33b2b838
Step 3/3 : ENTRYPOINT ["java","-jar","/app.jar"]
 ---> Running in b66e12cfae9a
Removing intermediate container b66e12cfae9a
 ---> 0a3b64bb0987
Successfully built 0a3b64bb0987
Successfully tagged tenmao/helloworld:latest
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

运行

  • 启动命令
E:Workspacedockerhelloworld>docker run -p 8080:8080 tenmao/helloworld
  • 结果如下图

运行

参考