参考:https://www.bilibili.com/video/BV1og4y1q7M4?p=1
一.在IDEA中构建项目
- 在IDEA中创建新的Maven项目
- 修改pom.xml文件,增加springboot的相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yqj</groupId>
<artifactId>springboot-docker</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 编写主启动类
package com.yqj.docker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DockerTestMain {
public static void main(String[] args) {
SpringApplication.run(DockerTestMain.class,args);
}
}
- 编写controller层的访问测试类
package com.yqj.docker.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 "Hello Docker";
}
}
- 启动本地的springboot服务,测试是否可以正常访问 http://localhost:8080/hello
- 若可以正常访问,则通过maven将项目打为jar包
- 编写Dockerfile文件
FROM java:8
MAINTAINER yaj<yaoqijun@outlook.com>
COPY *.jar /app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/app.jar"]
二.Docker构建镜像并运行容器
- 将生成的jar包与Dockerfile文件复制到linux服务器的某个目录中
- 使用Dockerfile构建镜像
docker build -t springboot-demo:1.0 .
- 启动容器
docker run -d -p 8080:8080 --name myspringboot springboot-demo:1.0
- 测试访问
curl http://localhost:8080/hello
Hello Docker
网友评论