Sample code for deploying Spring-boot project with Docker

Sample code for deploying Spring-boot project with Docker

1. Basic Spring-boot Quick Start

1.1 Quick start pom.xml adds the following dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
  </parent>

  <properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </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>
  </dependencies>

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

Spring-boot startup class

@SpringBootApplication
public class DockerApplication {

  public static void main(String[] args) {
    SpringApplication.run(DockerApplication.class, args);
  }
}

Testing the API

@RestController
public class DockerStarterApi {

  @GetMapping("/api/docker/hello")
  public String hello() {
    return "hello docker";
  }
}

Configure the startup configuration file application.yml

server:
 port: 9090 # To demonstrate the effect, the default port 8080 is changed here

Check Spring Boot

. ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|===============|___/=/_/_/_/
 :: Spring Boot :: (v2.0.2.RELEASE)

...

2018-12-17 17:26:13.385 INFO 48740 --- [ main] osjeaAnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-12-17 17:26:13.448 INFO 48740 --- [ main] osbwembedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path ''
2018-12-17 17:26:13.453 INFO 48740 --- [ main] pers.study.docker.DockerApplication : Started DockerApplication in 1.982 seconds (JVM running for 2.602)

Check whether the API is effective

$ curl -XGET 'http://localhost:9090/api/docker/hello'
hello docker

Browser Check

http://localhost:9090/api/docker/hello

1.2 Packaging and startup

Project Packaging

After completing the above steps, execute the packaging command:

$ mvn clean -U -Dmaven.test.skip compile package

Because finalName is defined in the pom file above, you can see here that spring-docker.jar will be generated in target directory after compilation and packaging.

<finalName>spring-docker</finalName>

Test run

$ java -jar target/spring-docker.jar

If nothing goes wrong (leave a message if you have any questions~), the running results are the same as above and check whether the API is effective.

2. Docker Quick Installation

Next, prepare Docker

Install

Download and install from the official website

Check installation, view help

$ docker --version
Docker version 18.06.0-ce, build 0ffa825

$ docker --help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
...

Mirror Acceleration

China official mirror acceleration

3. Configure Spring-boot + Docker

Add docker plugin to pom.xml

<properties>
    <docker.image.prefix>springboot</docker.image.prefix>
  </properties>

  <build>
    <plugins>
      <!-- Docker maven plugin -->
      <plugin>
        <groupId>com.spotify</groupId>
        <artifactId>docker-maven-plugin</artifactId>
        <version>1.0.0</version>
        <configuration>
          <imageName>${docker.image.prefix}/${project.build.finalName}</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>
    </plugins>
  </build>

Create a Dockerfile

According to the configuration of the pom.xml file above, <dockerDirectory>src/main/docker</dockerDirectory> , the directory of the docker configuration file is configured here, so you need to create a docker folder under src/main and create a Dockerfile file at the same time.

The directory structure is as follows:

Docker configuration file structure.png

Edit Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD spring-docker.jar app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

FROM indicates that the image is based on Java 8

VOLUME indicates the mount directory

ADD copies the packaged file and renames it to app.jar

According to the official documentation below, ENTRYPOINT is a system property added to shorten the startup time of Tomcat.

We added a VOLUME pointing to /tmp because that is where a Spring Boot application creates working directories for Tomcat by default. The effect is to create a temporary file on your host under /var/lib/docker and link it to the container under /tmp . This step is optional for the simple app that we wrote here but can be necessary for other Spring Boot applications if they need to actually write in the filesystem.

To reduce Tomcat startup time we added a system property pointing to "/dev/urandom" as a source of entropy. This is not necessary with more recent versions of Spring Boot, if you use the "standard" version of Tomcat (or any other web server).

Configuration is complete!

4. Docker starts Spring-boot

Enter module and execute:

$ mvn package docker:build

[INFO] Scanning for projects...

...

 ---> Running in e1f8aba72bdf
Removing intermediate container e1f8aba72bdf
 ---> 36a61c09f09a
ProgressMessage{id=null, status=null, stream=null, error=null, progress=null, progressDetail=null}
Successfully built 36a61c09f09a
Successfully tagged springboot/spring-docker:latest
[INFO] Built springboot/spring-docker
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.367 s
[INFO] Finished at: 2018-12-17T20:48:21+08:00
[INFO] ------------------------------------------------------------------------

View Mirror

$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
springboot/spring-docker latest 36a61c09f09a 2 minutes ago 123MB

Run the image

$ docker run -p 9090:9090 -t springboot/spring-docker
 . ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|===============|___/=/_/_/_/
 :: Spring Boot :: (v2.0.2.RELEASE)

2018-12-17 12:53:21.502 INFO 1 --- [ main] pers.study.docker.DockerApplication : Starting DockerApplication v1.0-SNAPSHOT on 94991c04be5d with PID 1 (/app.jar started by root in /)
2018-12-17 12:53:21.509 INFO 1 --- [ main] pers.study.docker.DockerApplication : No active profile set, falling back to default profiles: default

···

2018-12-17 12:53:25.255 INFO 1 --- [ main] osjeaAnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-12-17 12:53:25.337 INFO 1 --- [ main] osbwembedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path ''
2018-12-17 12:53:25.353 INFO 1 --- [ main] pers.study.docker.DockerApplication : Started DockerApplication in 4.485 seconds (JVM running for 5.346)

View Container

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
94991c04be5d springboot/spring-docker "java -Djava.securit…" 53 seconds ago Up 52 seconds 0.0.0.0:9090->9090/tcp quizzical_bhabha

Verify startup and access API

$ curl -XGET 'http://localhost:9090/api/docker/hello'
hello docker

At this point, the Docker deployment of spring-boot is complete.

5. Remove the image

Stop the container

$ docker stop 94991c04be5d
94991c04be5d

Deleting a container

$ docker rm 94991c04be5d
94991c04be5d

Deleting an image

$ docker image rm springboot/spring-docker
Untagged: springboot/spring-docker:latest
Deleted: sha256:36a61c09f09ab88cfe5a05f564deb57498682f4a6f3ec01d2a8c4fdc80ac1e41
Deleted: sha256:3f9aef70be6d4d43c205454d8874f10bc2f7280f70eb88cd1f04937b7965dd27
Deleted: sha256:9a5800e93615bb4c5128bb36d31ec494327c01f1a9a768c1ff538badf76628b9
Deleted: sha256:d9c66f907448fa9e61fd5f9267d7fcf8e1f4b52d0a20466414f2f45777261284

6. Other configuration functions

Adding Environment Properties

$ docker run -e "SPRING_PROFILES_ACTIVE=prod" -p 9090:9090 -t springboot/spring-docker

Start running in the background

$ docker run -p 9090:9090 -d springboot/spring-docker

Enable container debugging and modify Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ADD spring-docker.jar app.jar
ENV JAVA_OPTS ''
CMD java -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar app.jar

docker run

Copy the code as follows:
$ docker run -e "JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=5005,server=y,suspend=n" -p 9090:9090 -p 5005:5005 -t springboot/spring-docker

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Docker deployment springboot project example analysis
  • Complete steps for Spring Boot to quickly deploy projects using Docker
  • Java remote one-click deployment of springboot to Docker through Idea
  • Springboot integrates docker deployment to implement two ways to build Docker images
  • The solution for the Springboot project to build a war package docker package and not find static resources under resource
  • Implementation of Spring Boot application publishing to Docker
  • Spring Boot and Docker deployment practice
  • Springboot docker principle and project construction

<<:  Vue+node realizes audio recording and playback function

>>:  What to do if you forget your mysql password

Recommend

Introduction to HTML link anchor tags and their role in SEO

The <a> tag is mainly used to define links ...

Detailed explanation of the functions of each port of Tomcat

From the tomcat configuration file, we can see th...

Solve the problem of MySQL using not in to include null values

Notice! ! ! select * from user where uid not in (...

SQL method for calculating timestamp difference

SQL method for calculating timestamp difference O...

How to build a drag and drop plugin using vue custom directives

We all know the drag-and-drop feature of HTML5, w...

Differences and comparisons of storage engines in MySQL

MyISAM storage engine MyISAM is based on the ISAM...

How to enter and exit the Docker container

1 Start the Docker service First you need to know...

Tudou.com front-end overview

1. Division of labor and process <br />At T...

How to install php7 + nginx environment under centos6.6

This article describes how to install php7 + ngin...

Solution for importing more data from MySQL into Hive

Original derivative command: bin/sqoop import -co...

How to install Jenkins using Docker

Table of contents 1. Pull the image 2. Create a l...

Install MySQL 5.7.18 using rpm package under CentOS 7

I have been using MySQL recently. The article mys...