Introduction to the

Docker is an open source application container engine that isolates an application’s runtime environment (the various libraries and configurations on which the application runs) through containers, and is lighter than virtual machines (which are isolated at the operating system level). Another advantage of Docker is build once, run everywhere, which can be compiled once and run on all platforms (Windows, Linux, etc.).

The basic concept

Basic concepts of Docker:

  1. An image, similar to an image in a VIRTUAL machine, can be understood as an executable program.

  2. A Container, similar to a lightweight sandbox, can be thought of as a minimalist Linux environment. Docker engines use containers to run and isolate applications. A container is an application instance created by an image. You can create, start, stop, and delete containers. Containers are isolated from each other and do not affect each other.

  3. A repository is a repository where Docker centrally stores image files. Note the difference with Registry server (Registry server) : Registry server is a place to store the repository, generally there will be more than one repository; The warehouse is the place where images are stored. Generally, each warehouse stores one type of image, and each image is distinguished by tag. For example, the Ubuntu warehouse stores multiple versions of Ubuntu images (12.04, 14.04, etc.).

  4. A dockerfile is a configuration file that compiles images.

Docker basic commands:

  • Docker build: We only need to specify what programs are needed and what configuration depends on in the dockerfile, and then send the Dockerfile to the “compiler” Docker for “compilation”. The generated executable program is image.

  • Docker run: Runs an image, which is then a Docker container.

  • Docker pull: Download the image written by others from the Docker Hub (Docker Registry).

Common docker image commands

Add docker repository location

Install yum – utils:

yum install -y yum-utils device-mapper-persistent-data lvm2
Copy the code

Add warehouse address:

yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
Copy the code

Install the Docker service

yum install docker-ce
Copy the code

Start the Docker service

systemctl start docker
Copy the code

Search the mirror

docker search java
Copy the code

Download image:

If the version number is not added, the latest version is downloaded by default.

Docker pull nginx: 1.18.0Copy the code

List the mirror

Docker Images REPOSITORY TAG IMAGE ID CREATED SIZE nginx 1.18.0c2C45d506085 7 days ago 133MB nginx 1.17.0719cd2e3ed04 22 months ago 109MB java 8 d23bdf5b1b1b 4 years ago 643MBCopy the code

Remove the mirror

You must delete the container based on the image before deleting it.

Docker rmi -f imageID # -f Forcibly delete imageCopy the code

Delete all unreferenced images (select IMAGE whose ID is None) :

docker rmi `docker images | grep none | awk '{print $3}'`
Copy the code

Forcibly delete all mirrors:

docker rmi -f $(docker images)
Copy the code

Packaging image

Docker build -t mall/mall-admin: 1.0-snapshot docker build -t mall/mall-admin: 1.0-snapshotCopy the code

Create a mirror image

There are also two types of image creation:

  • Create the container using the existing image, modify it, and commit to generate the image
  • Create an image using Dockerfile

(1) Use the existing image to create containers for modification

Start the container with an image:

[root@xxx ~]# docker run -it Java :8 /bin/bash # [root@72f1a8a0e394 /]# vim # Command not found [root@72f1a8a0e394 /]# apt-get update # [root@72f1a8a0e394 /]# apt-get install vimCopy the code

Exit Exits the container and then looks at the program (container) running in the Docker:

[root@VM_0_7_centos ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS                       PORTS     NAMES
857aa43eeed4   java:8         "/bin/bash"              19 minutes ago   Exited (127) 4 seconds ago             gifted_blackburn
Copy the code

The container is converted into an image, and then Docker engine has our new image. The difference between this image and the original Java image lies in the addition of the VIm tool.

[root@VM_0_7_centos ~]# docker commit -m "java with vim" -a "tyson" 857aa43eeed4 tyson/java:vim sha256:67c4b3658485690c9128e0b6d4c5dfa63ec100c89b417e3148f3c808254d6b9b [root@VM_0_7_centos ~]# docker images REPOSITORY  TAG IMAGE ID CREATED SIZE tyson/java vim 67c4b3658485 7 seconds ago 684MBCopy the code

Run the new image:

[root@VM_0_7_centos ~]# docker run -it tyson/java:vim /bin/bash
root@88fead8e7db5:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@88fead8e7db5:/# touch demo.txt
root@88fead8e7db5:/# vim demo.txt
Copy the code

(2) Create an image using Dockerfile

A dockerfile tells a Docker build what to do.

# Which image is based on FROM Java :8 # MAINTAINER Tyson # Build Operation performed by the image RUN apt-get update RUN apt-get install vim # Copy local files to the image COPY ./* /usr/tyson/Copy the code

Build the image with the build command:

docker build -t="tyson/java:vim" .
Copy the code

-t is used to specify the user information and tag of the new image. The last dot indicates looking for a Dockerfile in the current directory.

Once the build is complete, you can view the resulting image through Docker Images.

Push image:

Docker tag mall/mall-admin: 1.0-snapshot Macrodocker /mall-admin: 1.0-snapshot # Push macroDocker /mall-admin: 1.0-snapshotCopy the code

docker hub

Docker officially maintains a DockerHub public warehouse, which contains a lot of commonly used images. In addition to downloading images from above, we can also publish (push) our own custom images to DockerHub.

  1. Docker Hub Login:docker login
  2. To push the local image to the Docker Hub, the image username must be the same as the Docker Hub username:docker push tyson14/java:vim

Example Modify the image storage location

  1. View the image storage location:

    docker info | grep "Docker Root Dir"
     Docker Root Dir: /var/lib/docker
    Copy the code
  2. Disable the Docker service:

    systemctl stop docker
    Copy the code
  3. Move the original image directory to the destination directory:

    mv /var/lib/docker /home/data/docker
    Copy the code
  4. Establish soft connection:

    ln -s /home/data/docker /var/lib/docker
    Copy the code
  5. The image storage location is changed.

Common docker container commands

The new container

Create and start a container (a docker container must have a foreground process to run. If no foreground process is running, the container considers it idle and exits. Create a foreground process first) :

docker run -it --name java java:8 /bin/bash docker run -p 33055:33055 --name nginx \ > -v /home/data:/home/data \ > Nginx :1.18.0 \ > -e TZ="Asia/Shanghai" # -d nginx:1.18.0 -d indicates that the container is running in background modeCopy the code
  • -p: maps host ports to container ports in the following format: Host port: container port.
  • –name: Specifies the container name. You can then use the container name to manipulate the container.
  • -e: Sets the environment variable of the container, where the time zone is set.
  • -v: mounts files on the host to containers in the following format: Host file directory: container file directory.
  • -d: indicates that the container runs in background mode. The terminal does not output any running information;
  • -i: Runs the container in interactive mode, usually with -t.
  • -t: allocates a terminal to a container. It is usually used together with -i.

Use it. If exit is used, the container is in exit state, not background. If you want to keep the container running instead of stopping it, you can exit it by pressing CTRL + P CTRL + Q. The container status is Up.

Check the container

The -a argument lists all containers in operation:

docker ps
Copy the code

Stop the container

Use the container name or container ID:

docker stop $ContainerName(or $ContainerId)
Copy the code

Force stop containers:

docker kill $ContainerName
Copy the code

Start the container

docker start $ContainerName
Copy the code

Restart the container

systemctl restart docker
Copy the code

Into the container

Enter the container named mysql and open the command line terminal. The container does not stop when exit is used.

docker exec -it mysql /bin/bash
Copy the code

Docker Attach can directly input the input of the machine into the container, and the output of the container will be directly displayed on the screen of the machine. Using Exit or CTRL + C causes the container to stop.

docker attach container_name/container_id
Copy the code

To create and run the container, use the docker run -it Tyson/Java :vim /bin/bash to directly enter the container command line interface.

After exiting the command line using exit, re-enter the container:

  1. Docker inspect –format “{{.state. Pid}}” nginx

  2. Enter the container according to the found container ID: nsenter –target 28487 –mount — UTS — IPC –net — PID

    [root@VM_0_7_centos ~]# docker inspect --format "{{.State.Pid}}" nginx
    28487
    [root@VM_0_7_centos ~]# nsenter --target 28487 --mount --uts --ipc --net --pid
    mesg: ttyname failed: No such device
    root@b217a35fc808:/# ls -l
    Copy the code

Remove the container

Delete the container according to ContainerName:

docker rm nginx
Copy the code

Delete containers by name wildcards, such as those starting with the name mall- :

docker rm `docker ps -a | grep mall-* | awk '{print $1}'`
Copy the code

Forcibly delete all containers:

docker rm -f $(docker ps -a -q)
Copy the code

Container log

View logs generated by ContainerName:

docker logs nginx
Copy the code

Dynamically viewing logs generated by containers:

docker logs -f nginx
Copy the code

Container IP

docker inspect --format '{{.NetworkSettings.IPAddress}}' nginx
Copy the code

Container startup mode

Always docker container update --restart=always $ContainerNameCopy the code

Resource usage

View the resource usage of the specified container, such as CPU, memory, network, and I/O status:

Docker stats nginx CONTAINER ID NAME CPU % MEM USAGE/LIMIT MEM % NET I/O BLOCK I/O PIDS B217a35FC808 nginx 0.00% 3.641MiB / 1.795GiB 0.20% 656B / 0B 11.3MB / 8.19kB 2Copy the code

View the resource usage of all containers:

docker stats -a
Copy the code

Disk Usage

Docker system DF TYPE TOTAL ACTIVE SIZE RECLAIMABLE Images 3 1 885.4MB 752.5MB (84%) Containers 1 1 1.258kB 0B (0%) Local Volumes 0 0 0B 0B Build Cache 0 0 0B 0BCopy the code

Execute container internal commands

[root@VM_0_7_centos ~]# docker exec -it nginx /bin/bash root@b217a35fc808:/# ll bash: ll: command not found root@b217a35fc808:/# ls -l total 80 drwxr-xr-x 2 root root 4096 Apr 8 00:00 bin drwxr-xr-x 2 root root  4096 Mar 19 23:44 bootCopy the code

Specify an account to enter the container:

docker exec -it --user root nginx /bin/bash
Copy the code

network

View the network:

docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
5f0d326b7082   bridge    bridge    local
af84aa332f22   host      host      local
741c1734f3bb   none      null      local
Copy the code

Creating an external network:

docker network create -d bridge my-bridge-network
Copy the code

Specify network when creating container:

docker run -p 33056:33056 --name java \
> --network my-bridge-network \
> java:8
Copy the code

Copy the file

Copy the current directory TPCH folder to the appropriate location of the mysql container:

Docker cp TPCH mysql56:/var/lib/mysql #mysql56Copy the code

docker-compose

Docker Compose is a tool for defining and running multiple Docker container applications. Configure multiple application services using a YAML file and deploy all configured services at once from this YAML file.

The installation

The curl -l https://get.daocloud.io/docker/compose/releases/download/1.24.0/docker-compose- ` ` uname - s - ` uname -m ` > /usr/local/bin/docker-composeCopy the code

Change the permission of a file to executable:

chmod +x /usr/local/bin/docker-compose
Copy the code

Check whether the installation is successful:

docker-compose --version
Copy the code

Common commands

Create and start the container (default docker-comemage.yml) :

Docker-compose up -d: docker-compose up -dCopy the code

Specify file startup:

docker-compose -f docker-compose.yml up -d
Copy the code

Stop all related containers:

docker-compose stop
Copy the code

List all container information:

docker-compose ps
Copy the code

Deploying multiple services

  1. Use docker-comemage.yml to define the service to deploy;
  2. Use the docker-compose up command to deploy all configured services at once.

Defining a configuration file

Ports: Specify the port mapping between hosts and containers (HOST:CONTAINER)

Volumes: Mounting the HOST directory to the HOST:CONTAINER

Link: Connect services of other containers (under the same network) (SERVICE:ALIAS)

services:
  elasticsearch:
    image: Elasticsearch: 7.6.2
    container_name: elasticsearch
    user: root
    environment:
      - "cluster.name=elasticsearch" Set the cluster name to elasticSearch
      - "discovery.type=single-node" Start in single-node mode
      - "ES_JAVA_OPTS=-Xms128m -Xmx128m" # set the JVM memory size to be used
    volumes:
      - /mydata/elasticsearch/plugins:/usr/share/elasticsearch/plugins The plugin file is mounted
      - /mydata/elasticsearch/data:/usr/share/elasticsearch/data Mount data files
    ports:
      - 9200: 9200
      - 9300: 9300
  logstash:
    image: Logstash: 7.6.2
    container_name: logstash
    environment:
      - TZ=Asia/Shanghai
    volumes:
      - /mydata/logstash/logstash.conf:/usr/share/logstash/pipeline/logstash.conf Mount the logstash configuration file
    depends_on:
      - elasticsearch # Kibana will start after ElasticSearch has started
    link:
      - elasticsearch:es You can use the es domain name to access elasticSearch
Copy the code

Start the service

Yml/docker-comemess. yml/docker-comemess. yml/docker-comemess. yml/docker-comemess. yml/docker-comemess. yml/docker-comemess. yml

docker-compose up -d
Copy the code

The Maven plugin builds the Docker image

Docker image repository

Docker registry:

docker run -d -p 5000:5000 --restart=always --name registry2 registry:2
Copy the code

Docker enables remote access

Docker open remote access port 2375, docker.

vi /usr/lib/systemd/system/docker.service
Copy the code

The modifications are as follows:

ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock ExecStart=/usr/bin/dockerd -H TCP: / / 0.0.0.0:2375 - H Unix: / / var/run/docker. The sockCopy the code

Unix: / / / var/run/docker. The sock: Unix socket, local client connect through the docker Daemon. TCP ://0.0.0.0:2375: TCP socket, which allows any remote client to connect to the Docker Daemon through port 2375.

Docker supports HTTP image uploading

Echo '{"insecure-registries":["192.168.3.101:5000"]}' > /etc/docker-daemon.jsonCopy the code

Restart the docker

To make the configuration take effect:

systemctl daemon-reload
Copy the code

Restart docker service:

systemctl restart docker
Copy the code

Open ports

firewall-cmd --zone=public --add-port=2375/tcp --permanent
firewall-cmd --reload
Copy the code

Build the Docker image

Add the docker-Maven-plugin dependency to the application’s POP.xml file:

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>1.1.0</version>
    <executions>
        <execution>
            <id>build-image</id>
            <phase>package</phase>
            <goals>
                <goal>build</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <imageName>mall-tiny/${project.artifactId}:${project.version}</imageName>
        <dockerHost>http://tysonbin.com:2375</dockerHost>
        <baseImage>java:8</baseImage>
        <entryPoint>["java", "-jar","/${project.build.finalName}.jar"]
        </entryPoint>
        <resources>
            <resource>
                <targetPath>/</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>
Copy the code

Related configuration description:

  • Executions. Execution. Phase: during building a docker maven packaged application is configured on the mirror;
  • ImageName: used to specify the imageName, mall-tiny is the warehouse name,${project.artifactId}Is the mirror name,${project.version}Is the version number;
  • DockerHost: the address of the docker server that is uploaded after packaging.
  • BaseImage: the baseImage on which the application depends, in this case Java;
  • EntryPoint: command executed when the docker container is started;
  • Resources. The resource. TargetPath: copies after packaging resource file to the directory;
  • Resources. The resource. Directory: need to copy the file directory, maven packaged application jar packages exist below the target directory;
  • Resources. The resource. Include: the need to copy the file, packaged good application jar package.

Change the domain name in application.yml to db. Docker container can be regarded as an independent virtual machine, mall tiny-Docker access localhost naturally can not access mysql, docker containers can be accessed through the specified service name DB, The db name can be specified when running the mall-tiny-Docker container.

spring:
  datasource:
    url: jdbc:mysql://db:3306/mall? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
Copy the code

Run Maven’s package command, and after successful execution, the mirror repository will generate a mall-tiny-Docker image.

Start mysql service:

docker run -p 3306:3306 --name mysql \ -v /mydata/mysql/log:/var/log/mysql \ -v /mydata/mysql/data:/var/lib/mysql \ -v / mydata/mysql/conf: / etc/mysql \ - e MYSQL_ROOT_PASSWORD = root \ - d mysql: 5.7Copy the code

Docker exec it mysql /bin/bash

Start the mall-tiny-docker service, use –link to indicate that the application is in the same network (you can specify –network when starting the container), and use db to access the mysql service:

Docker run -p 8080:8080 --name mall-tiny-docker --link mysql:db --link containName:alias -v /etc/localtime:/etc/localtime \ -v /mydata/app/mall-tiny-docker/logs:/var/logs \ -d Mall - tiny/mall - tiny - docker: 0.0.1 - the SNAPSHOTCopy the code