Deploy a simple Spring Boot database project using Docker.

Containerization is in fashion these days, so start messing around. Tried next, sometimes really want to be more convenient than virtual machine. In fact, at first is to use Redis, but Windows installation is not convenient, so I looked at the next Docker, basically out of the box, Docker Hub pull a Redis official image can be. Just recently learning Spring Cloud microservices, also try to deploy the Spring Boot project Docker.

In terms of content, this article is mainly a supplement to the official Documentation of Spring Boot. If you are good at English, you can directly visit references 6-7.

The basic concept and usage of Docker are elaborated here, which can be seen in reference 1-3.

Docker Configuration

Docker is generally installed in the Linux system, but Windows can also be used, download and install out of the box. Additional configuration is required:

1. Expose TCP ports, which can be connected and used in the Docker plug-in of IDEA.

2. Replace the official Docker warehouse and use Ali Cloud image acceleration. You can configure it on the Daemon.

Config IDEA Plugin

Docker itself has no GUI interface, so all maintenance and management must use the command line, which is quite troublesome. IDEA provides us with a simple Docker plug-in for Image and Container management.

Search for docker directly in the Settings, add a Docker Engine, configure the URL, wait for the following message after successful connection, it is ok. If the connection fails, check whether TCP port 2375 is exposed.

And then at the bottom, you can see the Docker TAB. The information in the command line is the same as that in the command line. Basic operations such as creation, deletion, and port mapping can be performed on it.

Then the Docker-related configuration is complete.

Create Spring Boot Project

The demo here is a Spring Boot database project. As before, just configure the basics.

<! --pom.xml-->
<groupId>com.example</groupId>
<artifactId>spring-docker</artifactId>
<version>1.0.0</version>
<name>spring-docker</name>

<properties>
  <java.version>1.8</java.version>
  <skipTests>true</skipTests>		
  <druid-spring-boot-starter.version>1.1.10</druid-spring-boot-starter.version>
  <dockerfile-maven-plugin.version>1.4.10</dockerfile-maven-plugin.version>
  <docker.image.prefix>springboot</docker.image.prefix>
</properties>

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${druid-spring-boot-starter.version}</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>
Copy the code
# application.yml
Configure database information
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://ip:port/test? serverTimezone=Hongkong&characterEncoding=utf-8&useSSL=false
    username: 
    password: 
Copy the code
// Spring Boot starts the class
@SpringBootApplication
@RestController
public class SpringDockerApplication {

    private final JdbcTemplate jdbcTemplate;
    public SpringDockerApplication(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @GetMapping("/")
    public Message index(a) {
        RowMapper<Message> rowMapper= new BeanPropertyRowMapper<>(Message.class);
        Message msg = jdbcTemplate.queryForObject("select * from message where k = ?", rowMapper,"msg");
        return msg;
    }

    public static void main(String[] args) { SpringApplication.run(SpringDockerApplication.class, args); }}Copy the code

Local access, successful operation indicates that Spring Boot has been configured. So here’s the containerization.

Containerize It

In fact, containerization is the process of creating Docker image, which needs to encapsulate jar packages. There are two specific ways:

  1. Create a Dockerfile and manually execute build and run.
  2. Use the dockerfile-maven-plugin.

Use Dockerfile

First, create a docker folder under SRC /main and create a Dockerfile with the following contents:

FROM openjdk:8-jdk-alpine
VOLUME /tmp
COPYSpring - docker - 1.0.0. Jar app. The jar
ENTRYPOINT ["java"."-Djava.security.egd=file:/dev/./urandom"."-jar"."/app.jar"]
Copy the code

Assuming you know something about Dockerfile, explain the above,

  • FROM… , indicates usingopenjdkAs a base image, the label is: 8-JDK-alpine, which means JDK version 1.8, lite.
  • VOLUME… , create aVOLUMEPoint to the/tmpThe content of the. This is where the Spring Boot application creates the working directory for Tomcat by default. The effect is in/ var / lib / dockerCreate a temporary file on the host under and link it to/tmpUnder the container.
  • COPY… , copy the jar file in the project and rename it asapp.jar.
  • ENTRYPOINT… , the implementation ofjava -jarStart the project.java.security.egd=file:/dev/./urandomThe goal is to shorten Tomcat startup time.

Next, use Maven to package a JAR and manually copy it to the SRC /main/docker directory.

Configure IDEA to build and run docker.

Set the following parameters:

  1. Name: indicates the Name of the created configuration file.
  2. Image tag, repository for creating images :tags.
  3. Container name: creates the Container name.
  4. Bind posts, port mapping, where the default port 8080 is mapped to port 8888 on the extranet.
  5. Finally IDEA concatenates the parameters into docker build & run commands.

Click on the Run. The image will be automatically built and run in the container.

Click the Log TAB of the container we just deployed to see the Log of the Spring Boot startup.

MySQL > connect to mysql. MySQL > connect to mysql.mysql

The 2019-08-27 10:37:04. ERROR 197 1 - [eate - 1939990953] com. Alibaba. Druid. Pool. DruidDataSource: The create connection SQLException, url: JDBC: mysql: / / 127.0.0.1:3306 / test? serverTimezone=Hongkong&characterEncoding=utf-8&useSSL=false, errorCode 0, state 08S01 com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure Caused by: java.net.ConnectException: Connection refused (Connection refused)Copy the code

This is due to a problem with the configuration of the database URL. A local database would normally write localhost or 127.0.0.0.1. But this address is unrecognized in the Docker container. So I can’t connect to the local database. Fortunately, Docker is installed with a virtual bridge that can communicate with the inside of the Docker container.

We can see this by typing ipconfig in CMD on the host.

C:\Users\mqy6289>ipconfig Windows IP configure Ethernet adapter vEthernet (DockerNAT): connect specific DNS suffix....... : IPv4 addresses............ : 10.0.75.1 subnet mask............ : 255.255.255.240 Default gateway............. : Ethernet adapter Ethernet: connect to a specific DNS suffix....... : Apac.arcsoft. Corp Local link IPv6 address........ : fe80:: C64:6e72:831:378C %13 IPv4 address............ : 172.17.218.99 subnet mask............ : 255.255.224.0 default gateway............. : 172.17.192.1Copy the code

In DockerNAT, the host IP is 10.0.75.1, change the DATABASE URL IP to this. After deleting the containers and images, perform the previous steps again. The deployment is successful.

Type http://127.0.0.1:8888/ into your browser and you’ll see Hello World. The entire Docker deployment process is complete.

For the previous network communication problem, we can type docker inspect Hello-world in CMD to view the container’s parameters. You can see that the IP address and gateway of the container are not in the same network segment and cannot communicate.

{
    "Networks": {
        "bridge": {
            "Gateway": "172.17.0.1"."IPAddress": "172.17.0.2"."MacAddress": "02:42:ac:11:00:02",}}}Copy the code

Use Maven Plugin

Before, we used IDEA to build and run the image after creating dockerfile. Similarly, we can integrate the construction of Docker image and container with Maven through Maven plug-in. The docker-maven-plugin plugin is still used by most bloggers, but it is not recommended to use this plugin. Spotify also recommends using the dockerfile-maven-plugin instead. The following configuration of POM.xml:

<plugin>
  <groupId>com.spotify</groupId>
  <artifactId>dockerfile-maven-plugin</artifactId>
  <version>${dockerfile-maven-plugin.version}</version>
  <configuration>
    <contextDirectory>src/main/docker</contextDirectory>
    <repository>${docker.image.prefix}/${project.artifactId}</repository>
    <tag>v1</tag>
  </configuration>
</plugin>
Copy the code

After the refresh, you can see the functions of the plugin in the Maven TAB of IDEA, which are mainly used for build, push and tag.

The default plugin will look for local TCP ://localhost:2375. If enabled, double-click dockerFile :build and the image will be built into the Docker.

As you can see, the entire build process is put into Maven. To run the container, select the appropriate image, create Container, and do a simple configuration.

Troubleshooting

1. The database cannot be connected.

The local database needs to be configured to support remote access. This configuration is usually not performed on Windows and may be ignored.

UPDATE USER SET HOST = The '%' WHERE USER = 'root';
FLUSH PRIVILEGES;
Copy the code

2. Access the terminal

Our base image is Java and should be without a terminal by default. If you want to view it, you can create a container

docker run -ti --entrypoint /bin/sh springboot/spring-docker:v1
Copy the code

Enter ls -al to see the app.jar file that was copied before

Summary

This article mainly describes how to deploy the Spring Boot project in Docker. For the writing method of Dockfile and the use of Maven plug-in, you can see reference 5-6, which has more details. Personally, I feel that this deployment method, which directly makes the JAR and the base environment into a Docker image, is too easy to monitor and manage. It might make more sense to create a basic Centos image, install a Java environment, and run the jar and configuration files directly into the container using bash over SSH connections, as in server deployment. Later, if there is a need for work, you can further in-depth study to see how to operate in actual production.

Reference

  1. Docker Get Started
  2. 30 minutes quick Start Docker tutorial
  3. Docker(1) : Docker introduction tutorial
  4. Spring Boot 2.0(4) : Use Docker to deploy Spring Boot
  5. Spring Boot with Docker
  6. Spring Boot Docker

Source Code

This article was first written in 2019-09-23 and the information described in this article may have changed. Please use it with caution.