Rest my daily service development will be the preferred SpringBoot, because of the ease of use of its own and comes with a variety of convenient features, such as ecology, today simply talk about how to run the application in Spring Boot Docker containers
Project to build
First, open the Idea, select initialize a Spring Boot application, and then enter all the way down until the Idea finished downloading dependencies, start coding
Here to write a simple interface:
@RestController @SpringBootApplication public class DemoApplication { @GetMapping("/hello") public String hello() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
Then run the following command to verify that the service is working:
mvn clean package -Dmaven.test.skip=true java -jar target/demo-0.0.1-SNAPSHOT.jar
Containerized
Here we begin container of this simple application Spring Boot
Create a file Dockerfile
First create a Dockerfile file in the root directory of the project, the main do not mess camelCase:
From java:8 VOLUME /tmp #将打包好后的Jar文件放到image中 Add target/demo-0.0.1-SNAPSHOT.jar app.jar # change file access and modification times RUN bash -c 'touch /app.jar' EXPOSE 8080 #容器启动的时候运行Jar文件 ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
构建镜像
接下来就去构建Docker镜像,不过通常这一步都会用Jenkins的去做:
docker build -t demo8 .
如果看到下面的输出说明执行成功了:
Sending build context to Docker daemon 14.84MB Step 1/6 : FROM java:8 ---> d23bdf5b1b1b Step 2/6 : VOLUME /tmp ---> Using cache ---> 91086d8b7c77 Step 3/6 : ADD target/demo-0.0.1-SNAPSHOT.jar app.jar ---> d161bed06e8b Step 4/6 : RUN bash -c 'touch /app.jar' ---> Running in 9fbaff628989 ---> 1fc0498bbb06 Removing intermediate container 9fbaff628989 Step 5/6 : EXPOSE 8080 ---> Running in a5c44244b267 ---> 3b5150c5bdd0 Removing intermediate container a5c44244b267 Step 6/6 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar ---> Running in b7a3baac9d47 ---> 23ef7cc5e1b0 Removing intermediate container b7a3baac9d47 Successfully built 23ef7cc5e1b0 Successfully tagged demo8:latest
Run-time image
After this step is to build complete, we began to run smoothly:
docker run -d -p 4000:8080 demo8
Then curl it just to see if the interface correctly:
± % curl localhost:4000/hello Hello World%
We see here is to map port 4000 to the 8080 port container, we look into the container to test:
± % docker ps !10172 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5f1b7f29a0b6 988ed6f466b5 "java -Djava.secur..." 29 minutes ago Up 29 minutes 0.0.0.0:4000->8080/tcp practical_jones ± % docker exec -it 5f1b7f29a0b6 /bin/bash root@5f1b7f29a0b6:/ curl localhost:8080/hello Hello World
to sum up
SpringBoot directly generates an executable JAR package after package, it is very natural for use in conjunction with Docker, just as demonstrated in this article is very simple.