Packaging and deployment of SpringBoot and Mysql application Docker

Keywords: Docker MySQL Spring Maven

This paper implements a simple springboot+mysql application (ip count based on user access and stored in mysql database), builds a docker image for the application, implements the deployment of docker container and the docking with mysql container

Docker installation

You can install docker desktop for windows directly, which also includes docker compose. The results can be verified by docker compose version. Generally, the following information will be output:

docker-compose version 1.25.4, build 8d51620a
docker-py version: 4.1.0
CPython version: 3.7.4
OpenSSL version: OpenSSL 1.1.1c  28 May 2019

docker image related commands:

  • docker images view all local images
  • docker rmi XXX delete the image with the specified name

Command related to docker container:

  • docker ps -a show all containers
  • docker ps displays the currently running container
  • docker start mysql container named mysql before restarting
  • docker stop mysql stop msyql container

Write Visitor application

For multi module applications, you can manually set the path to the non project root directory when creating a model. For example, when creating a module named test, manually changing the path to D:\dev2\project\backends\docker\test, a directory level docker will be added to facilitate the unified management by adding nginx, mysql and other directories in the same directory, so as to realize the docker transformation

If the current parent project is backends, after the module is created, the pom.xml An example of the file is as follows:

<?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>backends</artifactId>
        <groupId>pers.techlmm</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>dockercomp</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

The program is based on jpa to automatically create ddl statements. The function of the program is to count the access times according to the access value ip:

@RestController
@RequestMapping("/api/v")
public class VisitorController {

    @Autowired
    private VisitorRepository repository;

    @RequestMapping("/")
    public String index(HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        Visitor visitor = repository.findByIp(ip);
        if (visitor == null) {
            visitor = Visitor.builder().ip(ip).times(1L).build();
        } else {
            // Number of visits + 1
            visitor.setTimes(visitor.getTimes() + 1);
        }
        repository.save(visitor);
        return "ip " + ip + "access times:" + visitor.getTimes();
    }
}

Finally, through curl http://localhost:8080/api/v / or browser access, you will get the following results: IP 0:0:0:0:0:0:0:0:1 access times:7

At the same time, it can also be verified through TestRestTemplate

@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@Slf4j
public class VisitorControllerTest {

    @Autowired
    TestRestTemplate restTemplate;

    // Build request path
    URI uri = UriComponentsBuilder.fromUriString("/api/v/").build().toUri();

    @Test
    void indexTest() {
        String response = restTemplate.getForObject(uri, String.class);
        log.info(response);
    }
}

Create docker profile

Since the database link mode changes after deployment to the docker environment, an application needs to be added- docker.properties The specific contents of the document are as follows:

# The docker mode is that the database address needs to be replaced by the docker container to implement the reference. Here, MySQL test is specified through the -- link of docker run
spring.datasource.url=jdbc:mysql://mysql-test:3306/test
spring.datasource.username=root
spring.datasource.password=goodpine

Local packaging and operation

Now try the local packaging mode by pom.xml In the file path (such as D: \ dev2 \ project \ backends \ dockercomp \ app >), execute MVN clean package- Dmaven.test.skip The package can be completed. The packed executable jar will be placed in the target directory, such as app\target\dockercomp-1.0-SNAPSHOT.jar

Execute Java - jar dockercomp - 1.0 directly on the command line- SNAPSHOT.jar You can start the service.

Create Dockerfile file

stay pom.xml Under the same directory, add the name of Dockerfile file:

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
EXPOSE 8080
#Attention needs to be increased- Dspring.profiles.active=docker , to formulate the configuration information under the docker deployment mode
ENTRYPOINT ["java","-Dspring.profiles.active=docker","-jar","/app.jar"]

The above file means to copy all jars under target to app.jar And make the runtime profile the configuration corresponding to docker.

Docker deployment

Start mysql docker service

docker run --name mysql-test -e MYSQL_ROOT_PASSWORD=goodpine -e MYSQL_DATABASE=test  -p 3306:3306 -d mysql 

After startup, you can check the operation of the container through docker ps

Construction of visitor docker image

In the spring project root directory, execute the docker build. - t visitor docker, where - t xxx refers to labeling the image. The command generally obtains the following results:

E:\dev\2try\backends\dockercomp\app>docker build .  -t visitor-docker
Sending build context to Docker daemon  39.79MB
Step 1/5 : FROM openjdk:8-jdk-alpine
 ---> a3562aa0b991
Step 2/5 : ARG JAR_FILE=target/*.jar
 ---> Using cache
 ---> 25bff168a2b2
Step 3/5 : COPY ${JAR_FILE} app.jar
 ---> bac68174227c
Step 4/5 : EXPOSE 8080
 ---> Running in 904bc1180df7
Removing intermediate container 904bc1180df7
 ---> 1f234b6dbf72
Step 5/5 : ENTRYPOINT ["java","-Dspring.profiles.active=docker","-jar","/app.jar"]
 ---> Running in 0a2a351a3225
Removing intermediate container 0a2a351a3225
 ---> 2ee38fd2463a
Successfully built 2ee38fd2463a
Successfully tagged visitor-docker:latest

After the image is built, you can view all the images of the current machine through docker images:

PS C:\Users\123> docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
visitor-docker      latest              156aa35a495c        46 seconds ago      145MB
mysql               latest              30f937e841c8        4 weeks ago         541MB
redis               latest              f9b990972689        7 weeks ago         104MB
mongo               latest              3f3daf863757        8 weeks ago         388MB
nginx               latest              602e111c06b6        8 weeks ago         127MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
openjdk             8-jdk-alpine        a3562aa0b991        13 months ago       105MB
sath89/oracle-12c   latest              ee3351d51185        22 months ago       5.7GB

Run docker application

Finally, run the application with the following command:

docker run --link mysql-test:mysql-test --name visitorapp -p 8080:8080 visitor-docker

Special note: * * pay special attention to adding the link, otherwise you cannot connect to the specified database. **Link X: in Y, X refers to the running image name. Here is the alias of the mysql database service started above; y refers to the database image alias referenced in the configuration file

So far, the deployment of docker, a spring boot application based on mysql, has been completed. During the experiment, there are many pits, such as – link, etc., which I hope will help you.

reference material

  • After uploading the multi module maven project to github, you need to download it through MVN first idea:module Run it once, and then refresh all modules through the maven window to identify each module in the idea
  • To delete an image, you can first delete the corresponding container through docker rm XXX, and then delete the corresponding image through docker RMI visitor docker.
  • http://www.ityouknow.com/springboot/2018/03/28/dockercompose-springboot-mysql-nginx.html
  • https://docs.docker.com/compose/install/
  • https://spring.io/guides/gs/spring-boot-docker/

Posted by friedemann_bach on Sun, 21 Jun 2020 00:02:11 -0700