Docker是一个开源的应用容器引擎,它允许开发者将应用及其依赖打包到一个可移植的容器中。
一、依赖
<?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"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>docker</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><!-- Docker Maven Plugin --><plugin><groupId>com.spotify</groupId><artifactId>docker-maven-plugin</artifactId><version>1.2.0</version> <!-- 使用最新版本 --><configuration><imageName>springboot-demo/springboot-with-docker</imageName><dockerDirectory>src/main/docker</dockerDirectory><resources><resource><targetPath>/</targetPath><directory>${project.build.directory}</directory><include>${project.build.finalName}.jar</include></resource></resources></configuration></plugin><!-- End of Docker Maven Plugin --></plugins></build>
</project>
二、配置文件和启动类
server:port: 8088
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
三、Dockerfile
FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD docker-1.0-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
四、Controller
@Controller
public class HelloWorldController {@RequestMapping("/hello")@ResponseBodypublic Map<String, Object> showHelloWorld(){Map<String, Object> map = new HashMap<>();map.put("msg", "HelloWorld");return map;}
}
五、构建镜像
mvn clean package docker:build
docker images 查看镜像
六、运行容器
docker run -p 8088:8088 springboot-demo/springboot-with-docker
访问地址http://127.0.0.1:8088/hello,返回
{“msg”:“HelloWorld”}