创建springboot项目,编写一个简单的hello world controller
下面是效果图。
下面是pom.xml 文件。
1 <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"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.lmy</groupId> 4 <artifactId>springboot-docker</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 7 <parent> 8 <groupId>org.springframework.boot</groupId> 9 <artifactId>spring-boot-starter-parent</artifactId> 10 <version>1.5.3.RELEASE</version> 11 <relativePath /> 12 </parent> 13 14 <properties> 15 <java.version>1.8</java.version> 16 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 17 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 18 </properties> 19 <dependencies> 20 <dependency> 21 <groupId>org.springframework.boot</groupId> 22 <artifactId>spring-boot-starter-web</artifactId> 23 </dependency> 24 <dependency> 25 <groupId>org.springframework.boot</groupId> 26 <artifactId>spring-boot-starter-test</artifactId> 27 <scope>test</scope> 28 </dependency> 29 </dependencies> 30 <build> 31 <plugins> 32 <plugin> 33 <groupId>org.springframework.boot</groupId> 34 <artifactId>spring-boot-maven-plugin</artifactId> 35 </plugin> 36 </plugins> 37 </build> 38 </project>
下面是目录结构。
App.java代码
package com.lmy.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
HelloController.java代码
package com.lmy.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class HelloController { @GetMapping("/hi/{name}") public String sayHello(@PathVariable String name){ return "hi,"+name; } }
将springboot项目打包成jar包。
我是在pom中加入了maven build的plugin,右键project,选择Run As 选择maven build, 在goals中输入package
控制台出现下面的字样表示打包成功,
这时候在target文件夹中出现了build出来的jar包。
将这个jar包拷贝到dockerfile文件的同一级目录。
Dockerfile代码
FROM java:8
ENV REFRESHED_AT 2019-07-25
ADD springboot-docker-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c ‘touch /app.jar‘
ENV JAVA_OPTS=""
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
运行下面的命令创建镜像sudo docker build -t lmy/springboot_v1 .运行下面的命令创建运行容器,sudo docker run -d -p 8085:8080 lmy/springboot_v1
下面可以看到已经运行成功了。
原文地址:https://www.cnblogs.com/liumy/p/11247667.html
时间: 2024-10-09 00:53:47