Docker 1.0


1、 Initial docker

1. Docker concept

  • Docker is an open source application container engine
  • Born in early 2013, based onGoLanguage implementation, produced by dotcloud (later renamed docker Inc)
  • Docker allows developers to package their applications and dependency packages into a lightweight, portable container and then publish them
    To any popularLinuxOn the machine
  • Containers are completely sandboxed and isolated from each other
  • Very low container performance overhead
  • After 17.03, docker is divided into Ce (Community Edition) and EE (Enterprise Edition)

    Summary: docker is a container technology, which is mainly used to solve the problem of software cross environment migration and deployment

2. Install docker

Note: docker can run on MAC, windows, CentOS, Ubuntu and other operating systems. The following learning is to install docker based on centos7
Docker website

#1. Update the yum package to the latest version
yum update
#2. Install the required software package. Yum util provides the function of Yum config manager, and the other two are dependent on the devicemapper driver
yum install -y yum-utils device-mapper-persistent-data lvm2
#3. Set the yum source
yum-config-manager --add-repo
#4. Install docker and enter y in all input interfaces
yum install -y docker-ce
#5. Check the docker version and verify whether the installation is successful
docker -v

3. Architecture

Note: learning the docker architecture can let us know which parts of docker are composed, and then we can know how to operate docker

Docker 1.0

Note: the figure above is divided into three parts: clients, hosts and registries

The core part includes (image, container)
  • Image: the docker image is equivalent to a root file system. Like the official image ubuntu:16.04 It contains a complete set of root file system of the smallest system of Ubuntu 16.04.
  • Container: the relationship between image and container is just like the relationship between class and object in object-oriented programming. Image is a static definition, and container is the entity of image runtime. Containers can be created, started, stopped, deleted, suspended, etc.
  • Repository: the repository can be regarded as a code control center for storing images.

4. Configure docker image accelerator

Note: by default, it is from docker hub( the docker image, but it’s too slow, so the domestic image accelerator, USTC, is usually configured(, Alibaba cloud, Netease cloud, Tencent cloud

Different accelerator configurations may use different methods. Here we take alicloud accelerator as an example

  1. Log in to alicloud’s official website(
  2. Click – console
  3. Search for “image”
  4. Click the searched “container image service”
  5. Click “image accelerator”
    Docker 1.0
    Docker 1.0
  6. According to the operation document, paste the command to the command line to run
  7. Check whether the configuration is successful
    Command: cat / etc / docker/ daemon.json

2、 Docker command

Description: as shown in the figure below, it mainly introduces three parts of commands. The first part describes how to operate the docker service (daemon) in hosts, that is, the background daemons. The second part describes how to operate the image. The third part describes how to operate the container
Docker 1.0

1. Docker service related commands

  • Start docker service
    systemctl start docker
  • Stop docker service
    systemctl stop docker
  • Restart docker service
    systemctl restart docker
  • View docker service status
    systemctl status docker
  • Set the power on to start the docker service
    systemctl enable docker

2. Docker image related commands

  • View image: view all local images
    #View all images
    docker images
    #View all images的id
    docker images -q
  • Search image: fromDocker HubFind the required image on the official website
    Docker search image name
  • Pull image: download the image from the docker warehouse to the local. The image name format is name: version number. If the version number is not specified, it is the latest version by default. If you don’t know the image version, you can go to docker hub to search the corresponding image to view it.
    Docker pull image name
  • Delete image: delete the local image
    #Delete the specified local image according to ID
    Docker RMI image ID
    #Delete all local mirrors
    docker rmi `docker images -q`

3. Container related commands

Note: we mentioned the relationship between the image and the container; the container is created by running the image file, and the container is the entity of the image runtime.

  • View containers
    #View running containers
    docker ps
    #View all containers
    docker ps -a

    Docker 1.0

  • Create and start the container
    Docker run - parameter -- name = container name image name: the initialization instruction for the image version to enter the container
    #Example 1: automatically enter the container after creation, and automatically close the container after exit
    docker run -it --name=c1 centos:7 /bin/bash
    #Example 2: the container will not be entered immediately after creation. You need to enter the container by typing a command. After exiting the container, the container will not be closed automatically. It will continue to run in the background
    docker run -id --name=c2 centos:7
    #Parameter Description:
    #- I: keep the container running. Usually used with - T. After adding the IT parameters, the container will automatically enter the container after it is created, and it will automatically close after it is exited.
    #- t: reassigns a pseudo input terminal to the container, usually used with - I.
    #- D: run the container in guard (background) mode. To create a container to run in the background, you need to use docker exec to enter the container. After exiting, the container does not close.
    #- it: the container created is generally called interactive container, and the container created by - ID is generally called Guardian container.
    #-- Name: name the container you created.
    #If you do not write the image version number, the default is the latest version
  • Enter the container
    Docker exec parameter container name initialization command
    Example: docker exec - it C2 / bin / Bash
  • Exit container
  • Stop container
    Docker stop container name or container ID
  • Start container
    Docker start container name or container ID
  • Delete container
    #If the container is running, the deletion fails. You need to stop the container before deleting it
    Docker RM container name or container ID
  • View container information
    Docker inspect container name or container ID

3、 Data volume of docker container

1. Concept and function of data volume


  • After the docker container is deleted, is the data generated in the container still there?
  • Can docker container and external machine exchange files directly?
  • How to exchange data between containers

Data volume:

  • A data volume is a directory or file in the host
  • When the container directory and data volume directory are bound, no matter who changes, they will be synchronized to the other party immediately
  • A data volume can bind multiple containers
  • A container can also bind multiple data volumes
    Docker 1.0
    Docker 1.0
    Docker 1.0

Data volume function:

  • Container data persistence
  • Indirect communication between external machine and container
  • Data exchange between containers

2. Configure data volume

  • When you create a startup container, use the-vParameter setting data volume
    Docker run - V Host Directory (file): in container directory (file)
    //Example 1: binding a data volume
    docker run -it --name=c1 -v /root/data:/root/data_container centos:7 /bin/bash
    //Example 2: binding multiple data volumes
    docker run -it --name=c2 -v /root/data2:/root/data_container2 -v /root/data3:/root/data_container3 centos:7 /bin

    be careful:
    1. The directory (file) must be an absolute path;
    2. If the directory does not exist, it will be created automatically;
    3. Multiple data volumes can be bound

    At the beginning of learning, you can practice in the virtual machine, take the virtual machine as the host, create multiple containers in the host and bind the data volume to see whether the data can be exchanged and persisted

3. Data volume container

Docker 1.0

Description: as shown in the figure above, containers C1, C2 and C3 are not different in nature, except that C3 is bound to the data volume in the host, and C1 and C2 are bound to C3. In this way, C1 and C2 are equivalent to binding to the data volume.

//1. Create C3 container first
docker run -it --name=c3 -v /root/data:/root/volume centos:7
//2. Create C1 and C2 containers, and use the -- volumes from parameter to bind C3
docker run -it --name=c2 --volumes-from c3 centos:7
docker run -it --name=c1 --volumes-from c3 centos:7

Example: create the file c.txt in / root / volume of C2, and the file will appear in the / root / data directory of C1, C3 and host at the same time. It can be operated by itself for verification

4、 Docker application deployment

1. MySQL deployment

Deployment steps:

  • Search MySQL image
  • Pull MySQL image
  • Create container
  • MySQL in operation container
    Note: because the network service in the container cannot communicate with the external machine directly, but the external machine can communicate with the host of the container. Therefore, if the external machine needs to access the service in the container, it is necessary to map the port providing the service in the container to the port of the host, so that the external machine can access the port of the host, so as to indirectly access the service of the container. This operation is called port mapping.
  1. Search image
    docker search mysql
  2. Pull away the mirror image
    docker pull mysql:5.7
  3. create mirror
    #Create a MySQL directory under / root directory to store MySQL data information
    mkdir /root/mysql
    #Commands for creating containers
    docker run -id -p 3307:3306 --name=mysql -v /root/mysql/conf:/etc/mysql/conf.d -v /root/mysql/logs:/logs -v /root/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7
  • Parameter Description:
    • -p 3307:3306: put the container’s3306Port mapped to the host’s3307Port (not necessarily mapped to port 3307).
    • -v /root/mysql/conf:/etc/mysql/conf.d: set the host’s/root/mysql/confThe relationship between directory and container/etc/mysql/conf.dFor binding mount, this ismysqlThe configuration directory of.
    • -v /root/mysql/logs:/logs: set the host’s/root/mysql/logsDirectory and container/logsIt is used to bind and hang the log.
    • -v /root/mysql/data:/var/lib/mysql: set the host/root/mysql/dataCatalog and container/var/lib/mysqlThis is the data directory.
    • -e MYSQL_ROOT_PASSWORD=123456: initializationrootUser’s password
  1. Enter the container and operate mysql
    #Command to enter the container
    docker exec -it mysql /bin/bash
    #Enter MySQL
    mysql -uroot -p123456
    #Print data table
    show databases;
  2. MySQL in external machine connection container
    Docker 1.0

2. Tomcat deployment

  1. Search Tomcat image
    docker search tomcat
  2. Pull Tomcat image
    docker pull tomcat
  3. Create container, set port mapping and directory mapping
    #Create Tomcat directory under / root directory to store Tomcat data information
    mkdir /root/tomcat
    cd /root/tomcat
    #Create and run container
    docker run -id --name=tomcat -p 8080:8080 -v /root/tomcat:/usr/local/tomcat/webapps tomcat
  • Parameter Description:
    • -p 8080:8080:Map port 8080 of container to port 8080 of host
    • -v /root/tomcat:/usr/local/tomcat/webapps: mount the Tomcat directory in the host to the container webapps directory
  1. Using external machine to access Tomcat: an example
    #Create a file in the Tomcat directory of the host
    mkdir /root/tomcat/test
    #Create index.html
    vim /root/tomcat/test/index.html

    Docker 1.0

3. Nginx deployment

  1. Search nginx image

    docker search nginx
  2. Pull nginx image

    docker pull nginx
  3. Create container, set port mapping and directory mapping

    #Create nginx directory under / root directory to store nginx data information
    mkdir /root/nginx
    mkdir /root/nginx/conf
    cd /root/nginx/conf
    #Create in / root / nginx / conf / nginx.conf File, paste the following
    vim nginx.conf
    User nginx; # set the system user of nginx service
    worker_ Processes 1; # number of work processes
    error_ log  /var/log/nginx/ error.log  Error log of warn; # nginx
    pid        /var/run/ ; # PID when nginx starts
    events {
     worker_ Connections 1024; # the maximum number of connections allowed per process
    Http {# HTTP request configuration, an HTTP can contain multiple servers
     #Define content type
     include       /etc/nginx/mime.types;
     default_type  application/octet-stream;
     #Log format here main and access_ Main correspondence in log
     # $remote_ Addr: client address
     # $remote_ User: the user name of the HTTP client requesting nginx authentication. By default, the authentication module is not enabled and will not be recorded
     #$timelocal: time of nginx
     #$request: request method + route + HTTP protocol version
     #Status: http reponse status code
     # body_ bytes_ Send: the size of the response body
     # $http_ Referer: referer header information parameter, indicating the superior page
     # $http_ user_ Agent: user agent header information parameter, client information
     # $http_ x_ forwarded_ For: x-forward-for header information parameter
     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                       '$status $body_bytes_sent "$http_referer" '
                       '"$http_user_agent" "$http_x_forwarded_for"';
     #Access the log, and the following main means to use log_ The main format in format is recorded to the access.log in
     access_log  /var/log/nginx/access.log  main;
     #One of the advantages of nginx is efficient file transfer
     sendfile        on;
     #tcp_nopush     on;
     #Timeout time between client and server, in seconds
     keepalive_timeout  65;
     #gzip  on;
     Server {# HTTP service, a server can be configured with multiple locations
             Listen 80; # service listening port
             server_ Name localhost; # host name, domain name
             #charset koi8-r;
             #access_log  /var/log/nginx/host.access.log  main;
             location / {
                 Root / usr / share / nginx / HTML; # page directory
                 index   index.html  index.htm ; # default page
             #error_page  404              /404.html;
             #Redirect the error page of 500 502 503 504 to / 50x.html
             error_page   500 502 503 504  /50x.html;
             Location = / 50x. HTML {# matching error_ Page path specified by page
                 Root / usr / share / nginx / HTML; # the directory where the page is stored
             # proxy the PHP scripts to Apache listening on
             #location ~ \.php$ {
             #    proxy_pass;
             # pass the PHP scripts to FastCGI server listening on
             #location ~ \.php$ {
             #    root           html;
             #    fastcgi_pass;
             #    fastcgi_index  index.php;
             #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
             #    include        fastcgi_params;
             # deny access to .htaccess files, if Apache's document root
             # concurs with nginx's one
             #location ~ /\.ht {
             #    deny  all;
     include /etc/nginx/conf.d/*.conf;
    #Create and run the nginx container
    docker run -id --name=nginx -p 80:80 -v /root/nginx/conf/nginx.conf:/etc/nginx/nginx.conf -v /root/nginx/logs:/var/log/nginx -v /root/nginx/html:/usr/share/nginx/html nginx
  • Parameter Description:
    • -p 80:80: put the container’s80Port mapped to the host’s80Port.
    • -v /root/nginx/conf/nginx.conf:/etc/nginx/nginx.conf: add the/root/nginx/conf/nginx.confMount to container:/etc/nginx/nginx.conf. configure directory
    • -v /root/nginx/logs:/var/log/nginx: add the/root/nginx/logsDirectory mounted to container/var/log/nginx. Log directory
  1. Accessing nginx services using external machines: an example
    #Create it in the directory / root / nginx / HTML / of the host computer index.html file
    cd /root/nginx/html
    vim index.html

    Docker 1.0

4. Redis deployment

  1. Search redis image
    docker search redis
  2. Pull redis image
    docker pull redis:5.0.9
  3. Create container, set port mapping
    docker run -id --name=redis -p 6379:6379 redis:5.0.9
  4. Use external machine to connect redis
    #Install and run redis- cli.exe  Connecting to the redis container on the host
    redis- cli.exe  -H host IP address - P bound host port

5、 Dockerfile

Docker image is essentially a hierarchical file system.

1. Mirror production

  1. Container to mirror
    Docker commit container ID image name: version number
  2. Image to compressed file
    #Because the image cannot be transferred, it needs to be converted into a compressed file
    Docker save - O compressed file name image name: version number
  3. Convert compressed file to image
    #Convert the compressed file produced by image to image again
    Docker load - I compressed file name

2. Dockerfile

2.1 overview:

DockerfileIs a text file, which contains a list of instructions, each instruction to build a layer.DockerfileFinally, a new image is constructed based on the basic image. For developers, theDockerfileProvide one or more consistent development environment for the development team, which is convenient for project testing and operation.

2.2 key words:

keyword effect remarks
FROM Specifies the parent image Specifies which image the dockerfile is built on
MAINTAINER Author information Used to indicate who wrote this docker file
LABEL label Label can be used to indicate dockerfile instead of maintainer, which can be viewed in the basic information of docker image
RUN Execute the order The default format for executing a command is / bin / sh: run command or run [“command”, “Param1”, “param2”]
CMD Container start command Provides the default command to start the container, which can be used with entrypoint. The format is CMD command Param1 param2 or CMD [“command”, “Param1”, “param2”]
ENTRYPOINT entrance It is usually used in containers that are closed after execution
COPY Copy file When building, copy the file to the image
ADD Add file When building, adding files to the image is not limited to the current build context. It can come from remote services
ENV environment variable Specify the environment variable when building. You can use – e to override the format env name = value when starting the container
ARG Construction parameters Build parameters are only used at build time. If env exists, the value of Env with the same name always covers arg
VOLUME Define data volumes that can be mounted externally Specify the image directory of build. When the directory can be started, mount it to the file system. When starting the container, use the – V binding format volume [“directory”]
EXPOSE Exposed port Define the port to listen to when the container is running. Start the container and use – P to bind the exposed port format: expose 8080 or expose 8080 / UDP
WORKDIR working directory If the working directory inside the specified container is not created, it will be created automatically. If the absolute address is specified / used, if it is not at the beginning of / then it is the relative path of the previous workdir path
USER Specify the executing user Specify the user when the build or start is executed in run CMD enterprise
HEALTHCHECK health examination The command to specify the health monitoring of the current container is basically useless, because many times the application has its own health monitoring mechanism
ONBUILD trigger When the image with the onbuild keyword is used as the basic image, the onbuild command will be executed after the execution of from, but it will not affect the current image and is not very useful
STOPSIGNAL Send semaphore to host The stop signal instruction sets the system call signal that will be sent to the container to exit.
SHELL Specifies the shell to execute the script Specifies the shell used by run CMD entrypoint when executing commands

2.3 case 1

Custom centos7 image:
Requirements: 1. The default login path is/usr2. VIM can be used
Because the official centos7 image cannot be used in the container after it is createdvimAnd enter the container. The default directory is/

Implementation steps:

  • Define parent image:FROM centos:7
  • Define author information:MAINTAINER itheima <[email protected]>
  • Execute the install VIM command:RUN yum install -y vim
  • Define the default working directory:WORKDIR /usr
  • Define the command for container startup execution:CMD /bin/bash
  • Build image through dockerfile:Docker bulid – f dockerfile file path – t image name: version
#Create a dockerfile folder in the / root directory of the host computer to store the dockerfile file
mkdir /root/dockerfile

#Create dockerfile
touch my_sentos7

#Write the following to my_ Sentos7 file
FROM centos:7
MAINTAINER ws <[email protected]>
RUN yum install -y vim
CMD /bin/bash

#Execute the build mirror command
docker build -f /root/dockerfile/my_sentos7 -t myself_centos7:1.0 .

#View local image
docker images

#Through myself_ Centos7: 1.0 image building container
docker run -id --name=myself_centos7 myself_centos7:1.0

#Enter the container
docker exec -it myself_centos7 /bin/bash

#At this point, the / usr directory of the container is entered by default, and the VIM command can be used

3. Service arrangement

Overview: batch manage containers according to certain business rules

3.1 installation and use of docker compose

Docker ComposeIt is a tool for arranging multi container distributed deployment, providing command set to manage the complete development cycle of container application, including service construction, start and stop.

Use steps:

  • Using dockerfile to define running environment image
  • Using docker- compose.yml Define the services that make up the application
  • Run docker compose up to start the application
  1. Install docker compose

    #Compose now fully supports Linux, Mac OS and windows. Before installing compose, you need to install docker. Next, we will install the compiled binary package in the Linux system. 
    curl -L`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
    #Set file executable permissions 
    chmod +x /usr/local/bin/docker-compose
    #View version information 
    docker-compose -version
  2. Uninstall docker compose

    #Binary package installation, delete the binary file
    rm /usr/local/bin/docker-compose

6、 Docker private warehouse

1. Build docker private warehouse

  1. Pull private warehouse image

    docker pull registry
  2. Start private warehouse container

    docker run -id --name=registry -p 5000:5000 registry
  3. Verify whether it is built successfully

    #Open the browser and enter the address http: // private warehouse server IP: 5000 / V2/_ Catalog, see {"repositories": []} to indicate that the private warehouse has been built successfully
  4. modify daemon.json

    #Open and edit the file
    vim /etc/docker/daemon.json
    #Add the following to the file
    {"insure registers": ["private warehouse server IP: 5000"]}
    "registry-mirrors": [" "], // original content
    "Insure registers": [""] // new content
    #Function: used to let docker trust private warehouse address; pay attention to modify private warehouse server IP to its own private warehouse server real IP
  5. Restart docker service

    systemctl restart docker
    docker start registry

2. Docker private warehouse – upload image

1. Mark the image as the image of the private warehouse

Image name: image version number private warehouse server IP: 5000 / image name: image version number
docker tag centos:7
  1. Image of upload tag
    Docker push private warehouse server IP: 5000 / image name: image version number
    docker push

3. Docker private warehouse – pull image

  1. Pull image
    Docker pull private warehouse server IP: 5000/ centos:7
    docker pull

Sources of learning materials

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today Application of regular expression

1. Balanced group / recursive matching (?’ Group ‘), which is called the corresponding content of group, and counts it on the stack;(?’- Group ‘), and count the corresponding content named group out of the stack(?!) Zero width negative look ahead assertion. Since there is no suffix expression, attempts to match always failRegular example:,{0,1}”5″:\[[^\[\]]*(((?’Open’\[)[^\[\]]*)+((?’-Open’\])[^\[\]]*)+)*(?(Open)(?!))\],{0,1} Test […]