Spring Boot detail excavation (Docker deployment projects)

Today Docker use is very popular, especially in the first-line Internet companies, Docker use of technology can help companies to quickly expand the level of service, so as to achieve the ability to deploy resilient business. After the rise of the concept of cloud services, usage scenarios and range of Docker's further development, now under the increasingly popular micro-services architecture, the perfect combination of micro-services + Docker's, more convenient operation and maintenance of the micro-service architecture deployed landing.

What is the Docker

Docker was originally a project dotCloud internal company founder Solomon Hykes in France during the launch, which is an innovation company based dotCloud cloud services technology for many years, and in March 2013 to open-source Apache 2.0 license, the main project code on GitHub on maintenance. Docker project and later joined the Linux Foundation, and promote the establishment of an open container Union (OCI).

Docker belongs to a Linux package container, the container provides an easy to use interface, which is the most popular Linux container solutions. Docker will depend on the application and the program which is packaged in a file, run the file, it will generate a virtual container. Running in the virtual container, just like running on a real physical machine, with Docker, do not worry about environmental problems.

Overall, Docker fairly simple interface, users can easily create and use a container, put their applications into the container. The container may also be version management, copying, sharing, modifying, managing general code like the same.

Why use Docker

In addition to running application container which substantially does not consume additional system resources, such high performance applications, while the overhead of the system as small as possible. Traditional way of a virtual machine is running 10 different applications will start 10 virtual machines, while Docker only need to start the application to 10 isolated.

Specifically, Docker has a large advantage in the following aspects.

  • Faster delivery and deployment, developers can use a standard image to build a development of the container, after the completion of the development, operation and maintenance personnel can directly use this container to deploy code.
  • More efficient virtualization, running Docker container does not require additional hypervisor support, it is kernel-level virtualization, it is possible to achieve higher performance and efficiency.
  • Easier migration and expansion, Docker containers can run on almost any platform, including physical machines, virtual machines, public cloud, private cloud, PCs, servers and so on.
  • Easier management, use Docker, only small changes, you can replace a lot of conventional updating.
     

Docker related concepts

Docker is CS architecture, there are two concepts, as follows.

  • Daemon Docker : running on the host, Docker daemon, the user Docker client (Docker command) to interact with the Docker daemon.
  • Client Docker : Docker command-line tool, the user is the main way to use the Docker, Docker Docker Client returns the result to the user communication daemon, Docker Client can access the remote daemon Docker through the socket or RESTful API.

Docker composition has three main concepts, as follows.

  • Image Docker : Mirror is read-only mirror contains files needed to run. Container used to create a mirror, a mirror can run multiple Container; Dockerfile image by creating, can be downloaded from the Docker hub / registry.
  • Container Docker : Docker container is running component, a start image is a container, which is an isolated environment, do not affect each other a plurality of containers, to ensure the running of a vessel in a relatively safe environment.
  • Hub Docker / Registry : sharing and management Docker image, the user can upload or download the above image, the official address of the visit here , you can also build their own private Docker registry.

Mirror equivalent packaged version, running in the container after the start mirroring, the warehouse is loaded local storage mirroring.

Next, create a Spring Boot project, and then add Docker support to the project, and finally deploying the project.

Spring Boot project

In pom.xml, using its dependencies Spring Boot 2.x:

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

Adding web testing and dependence:

<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>

Create a DockerController, in which there is a index () method returns visit: Hello Docker!

@RestController
public class DockerController {

    @RequestMapping("/")
    public String index() {
        return "Hello Docker!";
    }
}

Start categories:

@SpringBootApplication
public class DockerApplication {

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

After completion of the project started, after a successful launch browser to access the Web site: HTTP: // localhost: 8080 / , page returns: Hello Docker !, Description Spring Boot project is properly configured.

Add Docker support project

Add Docker image name in pom.xml:

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

plugins added Docker build plug-ins:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!-- Docker maven plugin -->
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>1.0.0</version>
            <configuration>
                <imageName>${docker.image.prefix}/${project.artifactId}</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>
        <!-- Docker maven plugin -->
    </plugins>
</build>
  • $ {Docker.image.prefix}, custom image name
  • $ {Project.artifactId}, project artifactId
  • $ {Project.build.directory}, build directory, default target
  • ${project.build.finalName}, Output the name, by default ${project.artifactId}-${project.version}

Dockerfile create files in the directory src / main / docker, Dockerfile file that explains how to build the image.

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

This Dockerfile file is very simple, basic environment to build the JDK, Spring Boot Jar added to the mirror, the simple explanation.

  • FROM, expressed using JDK 8 environment based mirroring, if the mirror is not local will be from DockerHub download.
  • VOLUME, VOLUME point to the directory / tmp, since the Spring Boot using the built-in Tomcat container, Tomcat defaults to / tmp as the working directory, the effect of the command is: create in the host's / var / lib / docker directory temporary file and link it to the container / tmp directory.
  • ADD, copy and rename the file.
  • EntryPoint, Tomcat in order to shorten the startup time, adding system properties java.security.egd point / dev / urandom as ENTRYPOINT.

Add this Spring Boot project Docker depend completed, explain below what is Dockerfile?

Dockerfile Introduction

Docker image is a special file system, in addition to providing the desired containers run programs, libraries, resources, configuration files, etc., also it contains configuration parameters for the preparation run (e.g. anonymous volume, environment variables, user, etc.) . Image does not contain any dynamic data, its contents will not be changed after the construct.

Customized image is actually customize each layer of the added configuration file. If each layer can be modified, installation, construction, operation commands to write a script, the script used to construct customized image, then the problem can not be reused before mentioned, the mirror construct problems of transparency, volume issues it will be resolved, this script is Dockerfile.

Dockerfile is a text file which contains the instructions a section (Instruction), each instruction to build a layer, and therefore the content of each instruction, is to describe how to construct the layer should be. With Dockerfile, when you need to customize their own additional requirements, simply add or modify the instruction on Dockerfile, can regenerate the image, eliminating the trouble of knocking command.

Dockerfile file format is as follows:

##Dockerfile 文件格式

# This dockerfile uses the ubuntu image
# VERSION 2 - EDITION 1
# Author: docker_user
# Command format: Instruction [arguments / command] ..

#(1)第一行必须指定基础镜像信息
FROM ubuntu

# (2)维护者信息
MAINTAINER docker_user [email protected]

# (3)镜像操作指令
RUN echo "deb http://archive.ubuntu.com/ubuntu/ raring main universe" >> /etc/apt/sources.list
RUN apt-get update && apt-get install -y nginx
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf

# (4)容器启动执行指令
CMD /usr/sbin/nginx

Dockerfile divided into four parts: the base image information, maintainer information, operation instruction image, the container starts executing instructions. Must specify the start image name is based, will be described next generally maintainer information; back is mirroring operation instruction, such as instruction RUN. Each execute a RUN command to add a new layer image, and submitted; and finally command CMD, to indicate operation of the command execution container.

Spring Boot Docker deploy applications require the use of Dockerfile custom deployment scenario.

Build Environment

Docker is recommended to install in the Linux environment, Window environment to build more complex and error-prone, use Centos7 + yum install Docker environment is very convenient.

Docker installation

Docker package already included in the default CentOS-Extras source software, the Docker so you want to install, just run the following command yum:

yum install docker

After installation is complete, use the following command to start the docker services, and set it to boot:

service docker start
chkconfig docker on

LCTT Annotation, employed herein old sysv syntax, such as the use of new syntax CentOS 7 systemd supported, as follows:

systemctl start docker.service
systemctl enable docker.service

Use 'Docker China' Accelerator:

vi  /etc/docker/daemon.json

#添加后:
{
    "registry-mirrors": ["https://registry.docker-cn.com"],
    "live-restore": true
}

Restart:

systemctl restart docker

test:

docker version

Enter the above command returns the version information docker prove docker successful installation.

Install the JDK

yum -y install java-1.8.0-openjdk*
  • Configuration environment variable
  • Open vim / etc / profile
  • Add the following
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64 
export PATH=$PATH:$JAVA_HOME/bin 

After modifications are complete, to take effect:

source /etc/profile

Enter java -version returns the version information is properly installed.

MAVEN installation

Download visit here :

## 解压
tar vxf apache-maven-3.5.2-bin.tar.gz
## 移动
mv apache-maven-3.5.2 /usr/local/maven3

Modify environment variables, add the following lines in / etc / profile in:

MAVEN_HOME=/usr/local/maven3
export MAVEN_HOME
export PATH=${PATH}:${MAVEN_HOME}/bin

Remember to perform source / etc / profile so that the environment variables to take effect.

Enter mvn -version returns the version information is properly installed.

So that the entire build environment to configure complete.

Use Docker deployment Spring Boot project

Copy the project spring-boot-docker to the server, packaged test into the project path.

#打包
mvn clean package
#启动
java -jar target/spring-boot-docker-1.0.jar

After seeing the Spring Boot boot environment configuration log shows that there is no problem, then use DockerFile build a mirror.

mvn package docker:build

The first building may be a bit slow, when you see the following when building a successful show:

...
Step 1 : FROM openjdk:8-jdk-alpine
 ---> 224765a6bdbe
Step 2 : VOLUME /tmp
 ---> Using cache
 ---> b4e86cc8654e
Step 3 : ADD spring-boot-docker-1.0.jar app.jar
 ---> a20fe75963ab
Removing intermediate container 593ee5e1ea51
Step 4 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Running in 85d558a10cd4
 ---> 7102f08b5e95
Removing intermediate container 85d558a10cd4
Successfully built 7102f08b5e95
[INFO] Built springboot/spring-boot-docker
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 54.346 s
[INFO] Finished at: 2018-03-13T16:20:15+08:00
[INFO] Final Memory: 42M/182M
[INFO] ------------------------------------------------------------------------

Use docker images command to view the constructed image:

docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
springboot/spring-boot-docker   latest              99ce9468da74        6 seconds ago       117.5 MB

springboot / springboot-docker is that we build a good image, the next step is to run the Mirror:

docker run -p 8080:8080 -t springboot/spring-boot-docker

Use docker ps view mirror after the completion of the running start:

docker ps
CONTAINER ID        IMAGE                           COMMAND                  CREATED             STATUS              PORTS                    NAMES
049570da86a9        springboot/spring-boot-docker   "java -Djava.security"   30 seconds ago      Up 27 seconds       0.0.0.0:8080->8080/tcp   determined_mahavira

You can see the construction of a container are running, access the browser: HTTP: //192.168.0.x: 8080 / , returned:

Hello Docker!

Instructions Docker deployment Spring Boot project success!

Common Commands

In addition to the Docker command had used above, there are other commonly used commands, you can view the status of the vessel through these commands.

Pulling docker mirror:

docker pull image_name

See image on the host, Docker image stored in / var / lib / docker directory:

docker images

Remove the mirror:

docker rmi  docker.io/tomcat:7.0.77-jre7   或者  docker rmi b39c68b7af30

View the current vessel which is running:

docker ps

View all containers:

docker ps -a

Start, stop, restart vessel command:

docker start container_name/container_id
docker stop container_name/container_id
docker restart container_name/container_id

After starting a container background, if you want to enter into this container, you can use the attach command:

docker attach container_name/container_id

Delete command vessel:

docker rm container_name/container_id

Delete all stop container:

docker rm $(docker ps -a -q)

Docker view the current system information:

docker info

Download an image from the Docker hub:

docker pull centos:latest
docker pull centos:latest

These commands can be found by using the Docker's very flexible, can be made into a mirror to project management, deployment time directly download the corresponding version of the image can be run directly.

to sum up

Docker is the foundation of container technology, service orchestration, elastic expansion are dependent on the level of use Docker using Docker deployment Spring Boot project, the project may be the same as the repository management, without concern for the environment, migration and other issues. Spring Boot is the basis for the development of micro-services, Docker is the basis for deployment of the container, a combination of both easier to use micro-service architecture deployed landing operation and maintenance.

Guess you like

Origin blog.csdn.net/chehec2010/article/details/94638735