Let your Spring Boot application run quickly on Docker.


 

Precondition:

1. Docker is already installed on the server (my side is CentOS 7) (the installation steps are simple, refer to my last blog)

2.Java and Maven have been installed on the server.

 

After meeting the above conditions, we can begin:

1. Create a simple Spring Boot application with only one controller, DockerController, as follows:

package cn.bounter.docker.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/docker")
public class DockerController {

    @GetMapping
    public String get() {
        return "Hello Docker!";
    }

}

 

2. Add the dockerfile-maven-plugin plug-in to the POM file. Add the following build as follows:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!--Docker-->
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>dockerfile-maven-plugin</artifactId>
                <version>1.3.6</version>
                <executions>
                    <execution>
                        <id>default</id>
                        <phase>package</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <repository>bounter/${project.artifactId}</repository>
                    <buildArgs>
                        <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
                    </buildArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>

 

3. Create a Dockerfile in the same directory as the POM file. The contents are as follows:

FROM openjdk:8
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

 

4. Copy the application code to the server and execute it in the directory where POM is located:mvn clean package

 

5. View the created image:docker images

 

6. Create a container and run it:docker run -d -p 8080:8080 bounter/bounter-docker

 

7. Verification:curl localhost:8080/api/docker

 

The above is all the steps. Is it very simple? Just try it yourself. If there’s anything else you don’t understand, please refer to my Github address: https://github.com/13babybear/bounter-docker

Leave a Reply

Your email address will not be published. Required fields are marked *