Docker installation and learning

Install Docker

Docker is divided into two versions: CE and EE. CE is the community version (free, with a support period of 7 months), and EE is the enterprise version. It emphasizes security, pays for use, and has a support period of 24 months.

Docker CE is divided into three update channels: stable test and nightly.

On the official website, there are all kinds of Installation guide , this section mainly introduces the installation of Docker CE on CentOS.

1.CentOS installs Docker

Docker CE supports 64 bit version of CentOS 7, and the kernel version is required to be no less than 3.10. CentOS 7 meets the minimum kernel requirements, so we install docker in CentOS 7.

 

1.1. Uninstall (optional)

If you have previously installed an older version of Docker, you can uninstall it using the following command:

yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-selinux \
                  docker-engine-selinux \
                  docker-engine \
                  docker-ce

 

1.2. Install docker

First of all, we need to connect virtual machines and install yum tools

yum install -y yum-utils \
           device-mapper-persistent-data \
           lvm2 --skip-broken

 

Then update the local mirror source:

# Set docker image source
yum-config-manager \
    --add-repo \
    https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
sed -i 's/download.docker.com/mirrors.aliyun.com\/docker-ce/g' /etc/yum.repos.d/docker-ce.repo
​
yum makecache fast

 

 

Then enter the command:

yum install -y docker-ce

Docker CE is a community free version. Wait a moment and docker will be installed successfully.

 

1.3. Start docker

Docker applications need to use various ports to modify firewall settings one by one. It's very troublesome, so I suggest you close the firewall directly!

Before starting docker, be sure to close the firewall!!

Before starting docker, be sure to close the firewall!!

Before starting docker, be sure to close the firewall!!

 

# close
systemctl stop firewalld
# Disable boot firewall
systemctl disable firewalld

 

Start docker by command:

systemctl start docker  # Start docker service
​
systemctl stop docker  # Stop docker service
​
systemctl restart docker  # Restart docker service

 

Then enter the command to view the docker version:

docker -v
1.4. Configure image acceleration

The network speed of docker's official image warehouse is poor, so we need to set up domestic image service:

Refer to Alibaba cloud's image acceleration document: https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors

 

 

2. Install DockerCompose in centos7

 

2.1. download

Under Linux, you need to download through the command:

# install
curl -L https://github.com/docker/compose/releases/download/1.23.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

You can also upload to / usr/local/bin / directory.

 

2.2. Modify file permissions

Modify file permissions:

# Modify permissions
chmod +x /usr/local/bin/docker-compose

 

 

2.3.Base auto completion command:
# Completion command
curl -L https://raw.githubusercontent.com/docker/compose/1.29.1/contrib/completion/bash/docker-compose > /etc/bash_completion.d/docker-compose

If an error occurs here, you need to modify your hosts file:

echo "199.232.68.133 raw.githubusercontent.com" >> /etc/hosts

 

 

3.Docker image warehouse

The image warehouse can be built based on the DockerRegistry officially provided by Docker.

Official website address: https://hub.docker.com/_/registry

 

3.1. Simplified image warehouse

Docker's official Docker Registry is a basic version of docker image warehouse, which has the complete function of warehouse management, but there is no graphical interface.

The construction method is relatively simple, and the command is as follows:

docker run -d \
    --restart=always \
    --name registry \
    -p 5000:5000 \
    -v registry-data:/var/lib/registry \
    registry

 

The command mounts a data volume registry data to the / var/lib/registry directory in the container, which is the directory where the private image inventory puts the data.

visit http://YourIp:5000/v2/_catalog You can view the images contained in the current private image service

 

3.2. Version with graphical interface

Use DockerCompose to deploy DockerRegistry with image interface. The command is as follows:

version: '3.0'
services:
  registry:
    image: registry
    volumes:
      - ./registry-data:/var/lib/registry
  ui:
    image: joxit/docker-registry-ui:static
    ports:
      - 8080:80
    environment:
      - REGISTRY_TITLE=Intellectual education private warehouse
      - REGISTRY_URL=http://registry:5000
    depends_on:
      - registry

 

3.3. Configure Docker trust address

Our private server adopts http protocol and is not trusted by Docker by default, so we need to make a configuration:

# Open the file you want to modify
vi /etc/docker/daemon.json
# Add content:
"insecure-registries":["http://192.168.150.101:8080"]
# Reload
systemctl daemon-reload
# Restart docker
systemctl restart docker

 

Docker

Container data volume

Pit!!

Docker is linked to the host directory for access. If the permission is insufficient, you will be prompted

Solution: add one more -- privileged=true after the directory is mounted

introduce

  • The container data volume method can complete the data persistence and important data backup

  • Mapping, the data in the container is backed up + persisted to the local directory

  • It is similar to rdb ref in redis

What is it?

A volume is a directory or file. It exists in one or more containers and is mounted to the container by docker, but it does not belong to the federated file system. Therefore, it can bypass the Union File System and provide some features for continuous storage or sharing of data

The design of volume is data persistence, which is completely independent of the life cycle of the container. Therefore, Docker will not delete its mounted data volume when it is deleted in the container

What can I do

The application is packaged and mirrored with the running environment. After running, the container instance is formed to run, but our requirements for data are persistent

If the data generated by the Docker container is not backed up, the data in the container will naturally disappear after the container is deleted

In order to save data, we use data volumes

characteristic

  • Data volumes can be shared or reused between containers

  • Changes in the volume take effect directly in real time

  • Changes in the data volume are not included in the update of the mirror

  • The life cycle of a data volume continues until no container is used

 

How to use it?

#mount 
docker run -it   --privileged=true -v /Host absolute path directory:/In container directory[:rw]    Image name
​
#Check whether the data volume is mounted successfully
deocker inspect container id
​
#Inheritance between data volumes
docker run -it  --privileged=teue  from Sub name --name  Parent name
​

 

Read and write rules for data volumes and container files

  • [: rw] both host and container are readable and writable

  • [: ro] the host is readable and writable, and the container is only readable

 

DockerFile

introduce

Dockfile is a script interpreted by docker program. Dockerfile is composed of one instruction, and each instruction corresponds to one command under Linux. The docker program translates these dockerfile instructions into real linux commands. Dockerfile has its own writing format and supported commands. Docker program solves the dependency between these commands, similar to makefile. Docker program will read dockerfile and generate customized image according to the instructions.

The Dockerfile instruction ignores case. It is recommended to use uppercase and use # as annotation. Each line only supports one instruction, and each instruction can carry multiple parameters.

Dokerfile instructions can be divided into two types according to their functions: construction instructions and setting instructions. The build instruction is used to build an image, and its specified operation will not be executed on the container running the image; The set directive is used to set the properties of the image, and the specified operation will be performed in the container running the image.

 

What is it?

The command to create a new image is based on the command and the parameters of the Dockerfile, which are applied to the new image

What can I do

  • For developers: it can provide a completely consistent development environment for the development team;

  • For testers: you can directly take the image built during development or build a new image through Dockerfile file to start working;

  • For operation and maintenance personnel: seamless migration of applications can be realized during deployment.

Writing rules and instruction usage of Dockerfile

1,FROM(Specify basis image)
    # The build instruction must be specified and preceded by other instructions in Dockerfile. Subsequent instructions depend on the image specified by the instruction. The basic image specified by the FROM instruction can be in the official remote warehouse or in the tag version of the local warehouse.
    FROM <image>:<tag>
 
    FROM hub.c.163.com/netease_comb/debian:7.9
 
2,USER (Set the instruction and set the user who starts the container. The default is root user)
    # Specify the running user of memcached
    ENTRYPOINT ["memcached"]
    USER daemon
    or
    ENTRYPOINT ["memcached", "-u", "daemon"]
 
 
 
3,MAINTAINER((used to specify the image creator information)
    # The build instruction is used to write the information related to the image maker into the image. When we execute the docker inspect command on the image, there are corresponding fields in the output to record the information.
    MAINTAINER <name>
 
    MAINTAINER Alenx
 
 
4,RUN((for installing software)
    # Build instruction, RUN can RUN any command supported by the basic image. If ubuntu is selected for the basic image, the software management part can only use the command of ubuntu.
    RUN <command> (the command is run in a shell - `/bin/sh -c`)
    RUN ["executable", "param1", "param2" ... ]  (exec form)
 
    RUN apt-get install -y openssh-server apt-utils tomcat7
    RUN rm -rf /var/lib/apt/lists/*
 
 
5,CMD(set up container Actions performed at startup)
    # The setting instruction is used for the operation specified when the container is started. This operation can be to execute a custom script or execute a system command. The instruction can only exist once in the file. If there are multiple instructions, only the last one will be executed.
    CMD ["executable","param1","param2"] (like an exec, this is the preferred form)
    CMD command param1 param2 (as a shell)
    CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
 
    CMD echo hello world
 
6,ENTRYPOINT(set up container Actions performed at startup)
    # Setting instruction specifies the command to be executed when the container is started. It can be set multiple times, but only the last one is valid
    # The use of this instruction can be divided into two cases: one is used alone, and the other is used together with CMD instruction. When used alone, if you also use CMD command and CMD is a complete executable command, CMD instruction and ENTRYPOINT will overwrite each other, and only the last CMD or ENTRYPOINT is valid.
    ENTRYPOINT ["executable", "param1", "param2"] (like an exec, the preferred form)
    ENTRYPOINT command param1 param2 (as a shell)
 
    # CMD instruction will not be executed, only ENTRYPOINT instruction will be executed
    CMD echo "Hello, World!"
    ENTRYPOINT ls -l
 
    # Another usage is to specify the default parameter of ENTRYPOINT in combination with CMD instruction. At this time, CMD instruction is not a complete executable command, but only a parameter part; The ENTRYPOINT instruction can only specify the execution command in JSON mode, but cannot specify parameters
    FROM ubuntu
    CMD ["-l"]
    ENTRYPOINT ["/usr/bin/ls"]
 
 
7,EXPOSE(Specifies the port that the container needs to map to the host machine)
    """
        Set the instruction that maps the port in the container to a port in the host machine. When you need to access the container, you can not use the container IP Instead, use the address of the host machine IP Address and mapped port.
        To complete the whole operation, you need two steps, first in Dockerfile use EXPOSE Set the container port to be mapped, and then specify it when running the container-p Option plus EXPOSE Set the port so that EXPOSE The set port number will be randomly mapped to a port number in the host machine.
        You can also specify the port that needs to be mapped to the host machine. At this time, make sure that the port number on the host machine is not used. EXPOSE The command can set multiple port numbers at one time. When the corresponding container is running, it can be used multiple times-p Options.
        Port mapping is docker One of the more important functions is that each time we run the container, the container IP The address cannot be specified, but is randomly generated within the address range of the bridge network card.
        Host machine IP The address is fixed. We can map the port of the container to a port on the host machine, eliminating the need to view the container's address every time we access a service in the container IP Your address.
        For a running container, you can use docker port Add the port in the container that needs to be mapped and the name of the container ID To view the mapped port of the port number on the host machine
    """
    EXPOSE <port> [<port>...]
 
    # Map a port
    EXPOSE port1
    # The command used by the corresponding run container
    docker run -p port1 image
    # Map multiple ports
    EXPOSE port1 port2 port3
    # The command used by the corresponding run container
    docker run -p port1 -p port2 -p port3 image
    # You can also specify a port number that needs to be mapped to the host machine
    docker run -p host_port1:port1 -p host_port2:port2 -p host_port3:port3 image
    docker run -d -p 127.0.0.1:33301:22 centos6-ssh
 
 
8,ENV((used to set environment variables)
    # Build instruction, set an environment variable in image
    ENV <key> <value>
 
    # After setting, subsequent RUN commands can be used. After the container is started, you can view the environment variable through docker inspect, or set or modify the environment variable when docker run --env key=value.
    # If you have installed a JAVA program, you need to set up JAVA_HOME, you can write this in Dockerfile:
    ENV JAVA_HOME /path/to/java/dirent
 
9,ADD(from src Copy files to container of dest route
    """
        Build instructions, all copied to container File and folder permissions in are 0755, uid and gid 0; If it is a directory, all files in the directory will be added to the container In, excluding the directory;
        If the file is in a recognized compressed format, then docker Will help decompress (pay attention to the compression format); If<src>Is a file and<dest>If you do not end with a slash, the<dest>As a document,<src>The contents of the are written<dest>;
        If<src>Is a file and<dest>Ends with a slash in the<src>Copy files to<dest>Under the directory
    """
    ADD <src> <dest>
    # < SRC > is the relative path to the built source directory, which can be the path of a file or directory, or a remote file url;
    # < dest > is the absolute path in the container
 
 
10,VOLUME(Specify mount point)
    """
        Set the instruction so that a directory in the container has the function of persistent data storage. The directory can be used by the container itself or shared with other containers.
        We know that the container uses AUFS,This file system cannot persist data. When the container is closed, all changes will be lost. When the application in the container needs to persist data, you can Dockerfile Use this command in.
    """
    VOLUME ["<mountpoint>"]
 
    FROM base
    VOLUME ["/tmp/data"]
 
 
11,WORKDIR(Switch directory)
    # The setting instruction can be switched multiple times (equivalent to cd command) and takes effect for run, CMD and entrypoint.
    WORKDIR /path/to/workdir
 
    # Execute vim a.txt under / p1/p2
    WORKDIR /p1 WORKDIR p2 RUN vim a.txt
 
 
12,ONBUILD(Execute in sub mirror)
    # The command specified by ONBUILD is not executed when building the image, but in its sub image
    ONBUILD <Dockerfile keyword>

 

Docker network

brief introduction

When docker is started, a virtual bridge of docker0 will be started in the background, which can be viewed using ifconfig

Use docker0 for network communication between host and container

Network command mode

When we install docker After, three networks are automatically created by default
​
#View docker network commands
docker  network  ls
​
#View network data sources
docker  network  inspect  name
​
#Delete network
docker  network  rm  name
​
​

What can I do

  • Interconnection and communication between containers and port mapping

  • When the container ip changes, it can communicate directly with the network through the service name without being affected

Network mode

  • Bridge mode: specified by -- network bridge. docker0 is used by default

Assign and set IP for each container, and connect the container to a docker0

  • Host mode: use -- network host to specify

The container will not virtualize its own network card and configure its own IP, but use the IP and port of the host

  • None mode: use -- network none to specify

The container consists of an independent Network namespace, but no network settings are made for it, such as assigning veth pair, bridge connection, IP, etc

  • Container mode: use -- network container:NAME or container ID to specify

The newly created container will not create its own network card and configure its own IP, but specify a container to share IP and port range

Docker-Compose

What is it?

It is the official open source project of Docker, which is responsible for the rapid arrangement of Docker container clusters

You can manage multiple Docker containers to form an application. You need to define a configuration file in YAML format Docker compose yml

Write the calling relationship between multiple containers, and then you can start / close these containers at the same time with the next command

What can I do

Compose allows users to use a separate docker - compose YML to define a set of associated application containers as a project

It is easy to define a multi container application with a configuration file, and then install all the dependencies of the application with one instruction to complete the construction

Docker compose solves the problem of container and container Huang Zijian's management and arrangement

Core concepts of Compose

 

Compose common commands

# view help
docker-compose  -h
​
# Start all docker compose services
docker-compose  up 
​
# Start all docker compose services and run them in the background
docker-compose  up
​
# Stop and delete containers, networks, volumes, mirrors
docker-compose down
​
# Enter the container instance
docker-compose  exec  yml Services in id  /bin/bash
​
# Show all containers that have been run by the current docker compose orchestration
docker-compose  ps
​
# Show the container processes currently choreographed by docker compose
docker-compose  top
​
# View container output log
docker-compose  logs  yml Services in id
​
# Check configuration
docker-compose  config
​
# Check the configuration and output only those with problems
docker-compose  config  -q
​
# Restart service
docker-compose  restart
​
# Start service
docker-compose  start
​
# Out of Service
docker-compose  stop

 

General Command

Start Docker

sudo systemctl start docker

Stop Docker

sudo systemctl stop docker

Restart Docker

sudo systemctl restart docker

Restart Docker after modifying the configuration

sudo systemctl daemon-reload
sudo systemctl restart docker

View version

docker version

View Docker information

docker info

Docker help

docker --help

 

Mirror command

View the installed image on Docker

docker images

Search the image on Docker hub

docker search tomcat

Download Image

docker pull tomcat[:version]

delete mirror

# Take deleting tomcat as an example
docker rmi tomcat[:version]
# Delete by mirror ID
docker rmi -f image ID
# Delete multiple by mirror ID
docker rmi -f Image name 1:TAG Mirror name 2:TAG 
# Delete all
# docker images -qa: get all image ID S
docker rmi -f $(docker images -qa)

Container command

Run a container

docker run [options] image [command] [arg...]
​
​
Common parameters:
-d: Background run container,And return to the container ID
​
-i: Run container interactively,Usually with-t Simultaneous use
​
-p: Port mapping,Format as host(host)port:Container port
​
-t: Reassign a pseudo input terminal to the container,Usually with-i Simultaneous use
​
--name="name": Specify a name for the container
​
--dns 8.8.8.8: Specify a name for the container dns The server,The default is consistent with the host
​
--dns-search domain:Specify a name for the container DNS domain name,The default is consistent with the host
​
-h "hostname": Specifies the name of the container hostname
​
-e arg="value": Setting environment variables
​
-env-file=[]:Reads environment variables from the specified file
​
--cpuset="0-2" or --cpuset="0,1,2": Bind container to specified cpu function
​
-m: Set the maximum memory used by the container
​
--net="bridge": Specifies the network connection type of the container,support bridge/host/none/container Four types
​
--link=[]:Add link to another container
​
--expose=[]:Open a port or group of ports,The host uses random ports to map to open ports

example:

docker run --name mynginx -d nginx:latest
# Map multiple ports
docker run -p 80:80/tcp -p 90:90 -v /data:/data -d nginx:latest

View running Docker containers

docker ps
​
Common parameters:
# Displays all containers, including those that are not currently running
-a
# Displays recently created containers
-l
# Displays the N recently created containers
-n
# In silent mode, only the container ID is displayed
-q
# Do not truncate output
--no-trunc

Exit container

# WeChat official account: ITester software test stack
# Exit and stop
exit
# The container does not stop exiting
ctrl+P+Q

Start a container that has stopped

docker start container ID Or container name

Restart container

docker restart container ID Or container name

Stop container

docker stop container ID Or container name

Force stop container

docker kill container ID Or container name

Delete container

# Delete stopped containers
docker rm container ID Or container name 
# Force deletion of stopped or running containers
docker rm -f  container ID Or container name 
#Delete all running containers at once
docker rm -f $(docker ps -qa)

Copy files from container to Host computer

docker cp container ID Or container name:/File path and file name host address
example:
Copy container coco of tmp Under folder info.txt To the current location of the host
docker cp coco:/tmp/info.txt .

Log command

docker logs -f -t --tail 10 container ID Or container name

Parameter Description:

# Add timestamp
-t
# Follow the latest log print
-f
# Output the log of the last few lines
--tail Number of rows

example:

docker logs -f -t --tail 10 5b66c8ab957e

 

 

 

 

 

Added by Morpheus on Sun, 06 Mar 2022 15:03:26 +0200