Don’t make a fuss! Quickly pull you into Docker (recommended to collect)

Preface

This article uses Docker to deploy SpringBoot to help you quickly understand the simple use of Docker Demo level operations. I would like to write this article to novices who are just getting started. Don’t criticize the experts.

Through this article you will learn the following:

  1. What is Docker and Docker-specific terms

  2. Docker installation

  3. Quickly create a SpringBoot project

  4. Dockerization of SprngBoot project

Understand Docker and related terminology

To learn something, you must first understand how to use it. and some operational terms for using it.

It’s like when you go to a driving school to learn to drive, the instructor first tells you this is the steering wheel, that is the accelerator, and this is the brake. You must remember this to save your life at critical moments!

After introducing the basic operation of the car, the instructor will teach you how to start the car and start running slowly.

First of all, it needs to be explained that Docker is a container technology that isolates and packages programs. It is also called “lightweight” virtualization technology.

Regarding the differences between container technology and physical machines and virtual machines, you can refer to yibuchen’s 2 introductions on this topic:

  1. Comparison of physical machines, virtual machines, and containers (1)

  2. Comparison of physical machines, virtual machines, and containers (2)

Secondly, Docker has to mention three knowledge points: image, container, warehouse, the three elements that must be learned in Docker. So what do their specific codes mean? Let Xiaokui tell you slowly.

  • Mirror: It is equivalent to a root file system. For example, the official image ubuntu:16.04 contains a complete set of the root file system of the Ubuntu16.04 minimal system. Can be understood as a template for starting a container

  • Container: A container is actually a special process. Docker allocates an independent space for the process

  • Warehouse: It is used to store images. It can be understood as a warehouse dedicated to storing images.

The relationship between Image and Container is like classes and instances in object-oriented programming.

Mirrors are static definitions, and we generally use Dockerfile to build files to create custom images.

A container is the entity in which the image is run. Containers can be created, started, stopped, deleted, paused, etc.

Practical operation

Install Docker

You can directly go to https://hub.docker.com/ to download the installation package for download and installation. The premise is that you need to register an account.

?

The official provides two installation package connections: edge and stable. The differences between these two installation packages are as follows: edge: the early adopter version is released once a month, which may have certain problems; stable: the stable version is updated once a quarter, and the relatively stable version is initially released. Scholars recommend downloading stable and installing it.

Configuring Docker image acceleration

Click the docker icon in the taskbar and click Settings to configure the image acceleration address as shown below.

Picture

Image created by programmer Xiao Kui

For other image configurations, you can also refer to the novice tutorial:

https://www.runoob.com/docker/docker-mirror-acceleration.html

Optional image acceleration addresses are as follows:

  • The official Chinese image library address provided by Docker: https://registry.docker-cn.com

  • Qiniu Cloud Accelerator address: https://reg-mirror.qiniu.com

  • NetEase’s mirror address: http://hub-mirror.c.163.com

  • Alibaba Cloud mirror address: Each Alibaba Cloud account provides a unique address

For information about Alibaba Cloud image operations, please refer to: Docker (2) Using Alibaba Cloud docker image to accelerate By Lucifer_Lucifer

Build a SpringBoot project and dockerize it

Step 1: Create a maven project and introduce SpringBoot’s Parent dependency.

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

Step 2: Introduce SpringBoot web stater dependency.

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

Step 3: Add the finalName tag in the build tag to configure the name of the SpringBoot project executable jar package. The specific code is as follows:

 <finalName>demo</finalName>

The specific contents of pom.xml are as follows:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
         
    
    org.example
    demo
    1.0-SNAPSHOT

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

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

    

    
        <finalName>demo</finalName>
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                maven-compiler-plugin
                
                    1.8
                    1.8
                    true
                
            
        
    

Step 4: Create the SpringBoot startup class in the src/main/java directory. The specific code is as follows:

package cn.cxyxiaokui.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

}

Step 5: Create a Controller for testing. The specific code is as follows:

package cn.cxyxiaokui.demo.controller;

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

@RestController
public class HelloDockerController {
    @GetMapping("/hello")
    public String hello(){
        return "hello docker";
    }
}

Step 6: Create a Dockerfile in the demo project, the specific contents are as follows:

FROM openjdk:8

MAINTAINER zhuoqianmingyue [email protected]

COPY target/demo.jar /demo.jar

ENTRYPOINT ["java", "-jar", "/demo.jar"]

Dockerfile content introduction

# FROM The customized image is created based on the java:8 image.
FROM openjdk:8
# MAINTAINER Author's information
MAINTAINER zhuoqianmingyue [email protected]

#COPY Copy demo.jar in the target directory to the custom image.
COPY target/demo.jar /demo.jar

# Run the command executed by the program, which is equivalent to executing java -jar demo.jar in the command window
ENTRYPOINT ["java", "-jar", "/demo.jar"]

Step 7: Create the script build.sh to build the image in the demo project. The specific content is as follows:

#!/usr/bin/env bash
# Package the SpringBoot project
mvn package

# Create an image based on the Dockerfile configuration file in the current directory
docker build -t demo:latest .

demo:latest: demo represents the name of the image, and latest represents the version number.

The directory structure of the project is shown below:

├── Dockerfile
├── README.md
├── build.sh
├── pom.xml
└── src
    ├── main
    │ ├── java
    │ │ └── en
    │ │ └── cxyxiaokui
    │ │ └── demo
    │ │ ├── DemoApplication.java
    │ │ └── controller
    │ │ └── HelloDockerController.java
    │ └── resources
    │ └── application.properties
    └── test
        └── java
            └── cn
                └── cxyxiaokui
                    └── demo
                        └── DemoApplicationTests.java

Step 8: Select build.sh and right-click to select Run build.sh to execute the script, or execute the script through sh build.sh. The packaging process will be a bit slow, please wait patiently during the execution.

tomlee@MacBook-Pro-3 demo % sh build.sh

If the following content appears, the execution is successful!

[INFO] BUILD SUCCESS
[INFO] -------------------------------------------------- --------------------------
[INFO] Total time: 8.336 s
[INFO] Finished at: 2023-10-29T10:25:55 + 08:00
[INFO] -------------------------------------------------- --------------------------
Sending build context to Docker daemon 16.71MB
Step 1/4: FROM openjdk:8
8: Pulling from library/openjdk
Digest: sha256:86e863cc57215cfb181bd319736d0baf625fe8f150577f9eb58bd937f5452cb8
Status: Downloaded newer image for openjdk:8
 ---> b273004037cc
Step 2/4: MAINTAINER cxyxiaokui [email protected]
 ---> Running in e5d6be851ad3
Removing intermediate container e5d6be851ad3
 ---> 6978f6d0bc81
Step 3/4: COPY target/demo.jar /demo.jar
 ---> a2aefab244c3
Step 4/4: ENTRYPOINT ["java", "-jar", "/demo.jar"]
 ---> Running in 55854ea57bee
Removing intermediate container 55854ea57bee
 ---> 151bc5c33e07
Successfully built 151bc5c33e07
Successfully tagged demo:latest

After successful execution, you can view the generated image through docker images.

tomlee@MacBook-Pro-3 demo % docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
demo latest 151bc5c33e07 About a minute ago 543MB

To start a container through the demo:latest image, execute the following command:

docker run -idt -p 8080:8080 demo:latest

As shown below, the execution is successful

tomlee@MacBook-Pro-3 demo % docker run -idt -p 8080:8080 demo:latest
c5d686654d9134db642428073a69c2062de473c9b96bef553e184b79762f05d3

Introduction to image parameters for starting the demo project

docker run starts the container based on the image

  • -i runs the container in interactive mode, usually used with -t.

  • -t reassigns a pseudo input terminal to the container, usually used with -i.

  • -d runs the container in the background and returns the container ID.

  • -p specifies port mapping in the format: host (host) port:container port.

  • demo:latest Image name: Image version number.

docker ps to view running images

tomlee@MacBook-Pro-3 demo % docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f242ab8fb29f demo:latest "java -jar /demo.jar" 2 minutes ago Up 2 minutes 0.0.0.0:8080->8080/tcp
  • CONTAINER_ID:Container ID

  • IMAGE: specific image

  • COMMOND: The command executed by the running program

  • STATUS: the status of the container

  • PORTS: Ports mapped by the container

  • NAMES: Name of the container

View the SpringBoot project startup log through docker logs -f container ID. The specific operations are as follows.

tomlee@MacBook-Pro-3 demo % docker logs -f c5d686654d9134d

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

2023-10-29 02:28:44.622 INFO 1 --- [main] cn.cxyxiaokui.demo.DemoApplication : Starting DemoApplication v1.0-SNAPSHOT on f242ab8fb29f with PID 1 (/demo.jar started by root in /)
2023-10-29 02:28:44.631 INFO 1 --- [main] cn.cxyxiaokui.demo.DemoApplication: No active profile set, falling back to default profiles: default
2023-10-29 02:28:47.105 INFO 1 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat initialized with port(s): 8080 (http)
2023-10-29 02:28:47.146 INFO 1 --- [main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-10-29 02:28:47.147 INFO 1 --- [main] org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat/9.0.12
2023-10-29 02:28:47.168 INFO 1 --- [main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2023-10-29 02:28:47.309 INFO 1 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/sbe] : Initializing Spring embedded WebApplicationContext
2023-10-29 02:28:47.309 INFO 1 --- [main] o.s.web.context.ContextLoader: Root WebApplicationContext: initialization completed in 2584 ms
2023-10-29 02:28:47.361 INFO 1 --- [main] o.s.b.w.servlet.ServletRegistrationBean: Servlet dispatcherServlet mapped to [/]
2023-10-29 02:28:47.369 INFO 1 --- [main] o.s.b.w.servlet.FilterRegistrationBean: Mapping filter: 'characterEncodingFilter' to: [/*]
2023-10-29 02:28:47.369 INFO 1 --- [main] o.s.b.w.servlet.FilterRegistrationBean: Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2023-10-29 02:28:47.369 INFO 1 --- [main] o.s.b.w.servlet.FilterRegistrationBean: Mapping filter: 'formContentFilter' to: [/*]
2023-10-29 02:28:47.370 INFO 1 --- [main] o.s.b.w.servlet.FilterRegistrationBean: Mapping filter: 'requestContextFilter' to: [/*]
2023-10-29 02:28:47.725 INFO 1 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor'
2023-10-29 02:28:48.291 INFO 1 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat started on port(s): 8080 (http) with context path ''
2023-10-29 02:28:48.299 INFO 1 --- [main] cn.cxyxiaokui.demo.DemoApplication : Started DemoApplication in 4.481 seconds (JVM running for 5.866)

Starting a container through Docker can be understood as creating a Linux virtual machine and running our program in the virtual machine.

You can enter the container through docker exec -it container ID /bin/bash (it can also be understood as entering a Linux virtual machine).

Execute curl localhost:8080/hello to access and run the SpringBoot project locally on the virtual machine. The specific operations are as follows:

tomlee@MacBook-Pro-3 demo % docker exec -it c5d686654d91 /bin/bash
root@c5d686654d91:/# curl localhost:8080/hello
hello docker

Exit can be done by exiting the container.

You can directly access the SpringBoot project deployed by the image through the browser. The specific effect is as follows:

Picture

Image created by programmer Xiao Kui

About the pitfalls of using Windows systems

Xiao Kui used to use a Windows machine to execute localhost directly through the browser and could not access it.

Most of the introductions on Baidu on this issue are to check the IP of the virtual machine by executing docker-machine ip default. But after I executed it, it looked like this

Picture

Image created by programmer Xiao Kui

The command recommends that we view it through docker-machine ls. The specific operations are as follows:

Picture

Image created by programmer Xiao Kui

I am not very familiar with the docker-machine operation. I hope anyone who has solved the problem can send me a private message.

Although I did not obtain the IP of the virtual machine through docker-machine under the Windows system, I obtained it through another method. The specific operations are as follows:

Execute ipconfig to view the IP of the Docker virtual host. The specific operations are as follows:

Picture

Image created by programmer Xiao Kui

Then access the Demo project built with SpringBoot through IP.

?

It should be noted that the operating system of the machine I am currently using is MacOS.

Summary

All operations are completed here! Next, let’s make a simple summary. The specific steps to dockerize a SpringBoot are as follows:

  1. Create SpringBoot project

  2. Define a Dockerfile to create a custom image

  3. Start the container through a custom image.

  4. View logs for applications in containers and access running programs

Commonly used operating commands for images, containers, and Dockerfiles are as follows:

Command Purpose Example
docker images View the image list on the host docker images
docker pull Download the image to localhost docker pull redis:latest
docker search Find image docker search redis
docker rmi image name Delete image docker rmi demo
docker tag image ID user name/image source name (repository name): new tag name (tag) Tag the image docker tag 860c279d2fec zqmy/demo:5.3
docker ps View the starting container docker ps
docker ps -a View startup container history docker ps -a
docker run Start Container docker run -itd –name redis-test -p 6379:6379 redis
docker stop Stop the container docker stop a750ccbcad88
docker restart Restart the container docker restart a750ccbcad88
docker exec -it /bin/bash Enter container docker exec -it a750ccbcad88 / bin/bash
docker rm -f Delete container docker rm -f a750ccbcad88
docker log -f View container log output docker log -f a750ccbcad88

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Cloud native entry-level skill treeContainer (docker)Install docker16924 people are learning the system