1. Reference materials

Official documentation: docs.docker.com/docker-for-… Warehouse address: hub.docker.com/

2. The installation of the Docker

2.1. Components of Docker

  1. ** Docker image is like a template that can be used to create containers. A docker image can be used to create multiple containers, similar to Java classes

  2. Container: A Java instance created through a Class. The container can be thought of as a simple Linux system

  3. ** Repository: a place where images are stored,

    It is divided into common warehouse and private warehouse

    • Docker Hub: Foreign

    • Ali cloud: configure mirror acceleration

2.2. Environment Preparation

We have to have a server and we can operate it

  1. Linux Command Basics

  2. CentOS 7

  3. Connect to a remote server using Xshell (free version)

2.3. Install the docker

Docs.docker.com/engine/inst… Uninstall the old version

$ sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
Copy the code

Install the basic installation package

$ sudo yum install -y yum-utils
Copy the code

Set up the repository for the mirror

$ sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo # default is foreign
    
$ sudo yum-config-manager \
    --add-repo \
    https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo # Aliyun Mirror
Copy the code

Install the Docker engine

yum makecache fast
Copy the code

Install the Docker engine

Yum install docker-ce docker-ce-cli containerd. IO # docker-ceCopy the code

CentOS 8 Docker installation conflicts with Podman

yum erase podman buildah
Copy the code

Proceed with the installation

2.4. Start the docker

systemctl start docker # indicates that the startup is successful
Copy the code

docker version
Copy the code

docker run hello-world
Copy the code

docker images
Copy the code

2.5. Uninstall Docker

# remove dependencies
yum remove docker-ce docker-ce-cli containerd.io
# delete resource
rm -rf /var/lib/docker The default working path for docker
Copy the code

3. Common docker commands

I’ve used some of these names and I’m going to give you an overview.

Command Reference address:

Docs.docker.com/engine/refe…

3.1. Global commands

docker version Display basic docker information
docker info # System information, number of images and containersDocker -- help command# Full information
Copy the code

3.2. Mirror commands

3.2.1. The docker images

docker images # view images on all localhosts
--all , -a		Show all images (default hides intermediate images) # display all--digests Show digests --filter , -f Filter output based on conditions provided --format Pretty-print images using a Go template --no-trunc Don't truncate  output --quiet , -q Only show numeric IDs# display id only
Copy the code

3.2.2. docker search

-f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print search using a Go template
      --limit int       Max number of search results (default 25)
      --no-trunc        Don't truncate output
Copy the code

3.2.3. The docker pull

docker pull mysql # download mysql image, default tag, default latest version latest
Copy the code

# Specify version download
docker pull mysql:5.7
Copy the code

The advantage of tiered downloading is that different versions of the same part do not need to be re-downloaded.

3.2.4. The docker rmi

-f -f -f -f -f -f -f -f
docker rmi -f d1165f221234
# delete multiple ids separated by Spaces
docker rmi -f id id id
# delete all
docker rmi -f $(docker images -aq) # images-aq: delete all image ids recursively
Copy the code

3.2. Container commands

With the image to create containers, Linux, download a centos image to test learning

3.2.1. Create a container and start it

Docker run [Optional] image#Parameters that
#- name = "name"The container name is used to distinguish the container
#-it Runs in interactive mode and enters the container to view the contents
#-d Background running
#-p Port mapping Host port :: container port
#The -v volume mount
#- e configuration
Copy the code
#docker run -d -p 3310:3306 -v /home/mysql/conf:/etc/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD = 123456 - name mysql01 mysql: 5.7

Copy the code

3.2.2. Enter the container

docker exec -it 1de87c606832 /bin/bash
Copy the code

# docker attach 1de87c606832
Copy the code

Docker attach to the terminal where the container is being executed, does not start a new process

#Check the directory
ls
Copy the code

3.2.3. View containers

#View the running container
docker ps
#View the container that was running
docker ps -a
#Displays recently created containers. Set the number of containers to display
docker ps -a - n=? 
#Only the container number is displayed
docker ps -aq
Copy the code

3.2.4. Exit the container

#Container stop exit
exit
#The container does not stop exiting. Note that the input method must be in English, but not in Chinese
Ctrl + P + Q
Copy the code

3.2.5. Delete containers

#Deleting a specified container The running container cannot be deleted if rm -f is forcibly deletedDocker RM Container ID#Delete all containers
docker rm -f $(docker ps -aq)
#Delete all containers
docker ps -a -q|xargs docker rm
Copy the code

3.2.6. Import and export

docker export $CONTAINER_ID > ubuntu.tar
Copy the code

$ cat docker/ubuntu.tar | docker import - test/ubuntu:v1
Copy the code

3.2.7. Automatic restart

Docker run --restart=always container id (or container name)#No-container: does not restart the container
#On-failure-container: restarts when the exit status is not 0
#Always: Always restartsDocker update --restart=always container id (or container name)Copy the code

3.2.8. Related status

docker start $CONTAINER_ID
docker restart $CONTAINER_ID
docker stop $CONTAINER_ID
docker kill $CONTAINER_ID
Copy the code

3.3. Other commands are commonly used

3.3.1. Background start Docker

Docker run -d specifies the image name#Docker PS was used to check and found that it stopped

#When the container is started, Docker will immediately stop when it finds that it does not provide services
Copy the code

3.3.2. View logs

Docker logs docker logs -f --tail=20 $CONTAINER_ID #Copy the code

3.3.3. Viewing container Information

docker inspect $CONTAINER_ID 
Copy the code

3.3.4. File copy

The container is copied to the host

Docker cp $CONTAINER_ID: Path space Specifies the host pathCopy the code
docker cp 83b0be074d94:/etc/mysql /home
Copy the code

Host copy to container

Docker cp Host path space $CONTAINER_ID: pathCopy the code

We will encounter volumes later

###3.3.5. Task Manager

docker stats
Copy the code

4. Container data volume

In Docker, in order to persist data, the data should not be in the container, otherwise the container will be deleted and the data will be lost. Therefore, there should be a data sharing technology between containers, which synchronizes the data generated in Docker containers to the local, which is called volume technology.

advantages

  1. Container persistence and synchronization operations

  2. Data can be shared between containers

4.1. Using a Data Volume

Currently Docker provides three different ways to mount data from the host machine to the container:

Volumes: run the /var/lib/docker-/ volumes directory to manage the host file system. (Most commonly used)

“Bind” means that it can be stored anywhere on the host system. (More common way)

However, bind mount is not portable between different host systems. For example, the directory structures of Windows and Linux are different, and the host directory to which bind mount points is not the same. This is why bind mount cannot appear in a Dockerfile, because then the Dockerfile is not portable.

(3) TMPFS: it is mounted and stored in the memory of the host system, but not written to the file system of the host; (In a way you wouldn’t normally)

4.1.1. Command mount

Docker run it -v -p/host host absolute path :/ container directory: permission image name#- IT Interactive access
#-v volume technology
#-p Host port
Copy the code
#mountdocker run -d -p 3306:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql -d Background running -p port mapping -v volume mounting -e Environment configuration --name Container nameCopy the code

The host directory /home/mysql.conf is synchronized with the /etc/mysql.conf container directory.

View its information

Soruce: indicates the host address

Destination: indicates the container address

4.1.2. Anonymous and Named mounts

Anonymous mount: The volume is mounted to only the path inside the container, not the path outside the container.

#-v Indicates the path inside a container
docker run -d -P --name nginx01 -v /etc/nginx nginx
Copy the code

** Named mount: ** is a mounted volume with its own name, you can easily find

#-v Volume name :/ Inside container path
docker run -d -P --name nginx01 -v wyl-nginx:/etc/nginx nginx
Copy the code

docker inspect 6d4a76d84a35
Copy the code

4.1.3. Viewing volume information

docker volume inspect wyl-nginx
Copy the code

4.1.4. Changing read/write permissions on files

# ro: readonly
# rw: readwrite
#Specifies the container's read and write permissions on the content we mount
docker run -d -P --name nginx01 -v nginxconfig:/etc/nginx:ro nginx
docker run -d -P --name nginx01 -v nginxconfig:/etc/nginx:rw nginx
Copy the code

4.2. View all data volumes

docker volume ls
Copy the code

4.3. The Shared volume

docker run -it --name nginx03 --volumes-from nginx02 nginx:latest
Copy the code

Nginx03 inherited the volumes of Nginx02

You can verify that adding data under Nginx02 will also appear under Nginx03

Deleting container shared files will not be deleted.

5.dockerFile

A Dockerfile is a text file used to build an image. The text content contains the instructions and instructions required to build the image.

5.1. The command

FROM Basic mirroring such as centos
MAINTAINER # who wrote the mirror name + email
RUN Commands to run when the image is built
ADD Add, for example, a Tomcat package
WORKDIR # mirror working directory
VOLUME # Mount directory
EXPOSE # specify exposed port, same as -p
RUN # finally run
CMD # specifies the command to run when the container is started. Only the last command is valid and can be replaced
ENTRYPOINT Specifies the command to run when the container is started. You can append the command
ONBUILD Run the ONBUILD command when building an inherited Dockerfile
COPY Copy the file to the image
ENV Set environment variables at build time
Copy the code

Create centos 5.2

Create dockerfile 5.2.1)

#Go to the home directory
cd /home

#Create a directory and save everything from there
mkdir dockerfile
#Go into this directory
cd dockerfile/
#Create a dockerFile called myDockerFile
vim mydockerfile-centos
Copy the code
FROM centos
MAINTAINER wyl<1714404171@qq.com>

ENV MYPATH /usr/local
WORKDIR $MYPATH

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 8088

CMD echo $MYPATH
CMD echo "---end---"
CMD /bin/bash
Copy the code

5.2.2. The docker build

cd /home/docerfile
docker build -t mycentos -f mydockerfile-centos .
Copy the code

Don’t forget the last point

6.Docker Compose

Before we use Docker, define Dockerfile file, and then use Docker build, Docker run and other commands to operate the container. However, the application system of microservice architecture generally contains several microservices, and each microservice will generally deploy multiple instances. If each microservice has to be started and stopped manually, the low efficiency and large maintenance amount can be imagined. Docker Compose

It is an application tool for defining and running multicontainer Dockers

6.1. Compose the installation

Sudo curl - L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname - s) - $(uname -m)" - o /usr/local/bin/docker-compose or sudo curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.1/docker-compose- ` ` uname - s - ` uname -m ` - o /usr/local/bin/docker-composeCopy the code

PIP install

sudo pip install docker-compose
Copy the code

6.2. Permissions

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

Pose using 6.3.Com

Three steps:

  • Use Dockerfile to define your application’s environment.

    FROM java:8
    VOLUME /tmp
    ADD docker-demo.jar app.jar
    RUN bash -c 'touch /app.jar'
    EXPOSE 9000
    ENTRYPOINT ["java"."-Djava.security.egd=file:/dev/./urandom"."-jar"."app.jar"]
    Copy the code
  • Use docker-comemage.yml to define the services that make up the application so that they can run together in an isolated environment.

    Compose and Docker compatibility: the Compose file format is composed in 3 versions, which are 1, 2. X and 3. X, respectively. The first level of key below the compose file is the name of the service. Build specifies the path containing the build context. Context # context: specifies the path where the dockerfile file is located. Dockerfile # dockerfile: Specify the name of the Dockerfile in the directory specified by context (default Dockerfile) args # args: Cache_from # v3.2; cache_from # v3.2; Set image labels # v3.3 as docker container build -- cache_FROM = labels # v3.3 Set image metadata (equivalent to docker container build --labels) shm_size # v3.5 Docker container build --shm-size specifies the size of the container /dev/shm partition. Shell format and [] format configs # cgroup_parent # container_name # Specifies the name of the container (same as docker run --name) credential_spec # The deploy part is used by The Docker Stack, Docker swarm endpoint_mode # v3.3 docker swarm endpoint_mode # v3.3 Docker stack DNSRR # DNS polling, Docker sets DNS entries for the service, so that the DNS query of the service name returns a list of IP addresses, and the client directly accesses an address labels # for the service. These tags are only used on the service to set mode # specify deploy's mode global # only one container replicated per cluster node # Users can specify the number of containers in the cluster (default) Placement # replicas # deploy's Resources # resource limits # set the resource limit of the container: "0.5" # set this container to use up to 50% of THE CPU memory: Reservations in cpus: "0.2" # Reserved 20% OF CPU memory for this container: Restart_policy specifies the container restart policy. Condition # defines the container restart policy (three parameters are accepted) None # Do not attempt to restart on-failure # Will only restart if there is a problem with the container internal application any # will try to restart anyway (default) delay # Window # Number of attempts to restart the container before the restart is successful (if the container is started, the number of seconds after the container is detected to check whether it is normal, Default 0s) update_config # Used to configure rolling update configuration Parallelism # Number of containers updated at one time delay # Interval between updating a group of containers failure_action # Define update failure policies continue # Rollback # Pause # Pause updates (default) Monitor # Duration after each update to monitor whether the update failed (unit: Ns | us | | | s | m h ms) (the default is 0) # max_failure_ratio rollback tolerate failure (the default value of 0) during new parameters in the order # v3.4 version, Stop-first # The old task is stopped before the new task is started (default) start-first # The new task is started first, and the running tasks temporarily overlap. Parallelism is used to define the rollback policy for failed update_config updates. If set to 0, Delay # Time interval between rollback of each group (default: 0) Failure_action # Define a rollback failure policy continue # Continue rollback pause # Pause monitor # Duration after each rollback task to monitor failure (unit: Ns | us | | | s | m h ms) (the default is 0) # max_failure_ratio rollback tolerate failure (the default value of 0) during the order # stop during a rollback operation order - first # old task before starting a new task to stop start - the first (default) # Start new tasks first, and running tasks temporarily overlap Docker-compose UP and docker-compose run are supported, but the docker stack deploy suboption security_opt container_name devices TMPFS is not supported Stop_signal links cgroup_parent network_mode external_links restart build userns_mode syscTLS Devices # Specify device mapping list (equivalent to Docker run - depends_on # Specifies the order of container startup (docker run - depends_on # specifies the order of container startup (docker run - depends_on # specifies the order of container startup)Copy the code
  • Finally, execute the docker-compose up command to get the entire application up and running.

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

    6.3. Uninstall

#PIP uninstall
pip uninstall docker-compose
Copy the code

6.4. Common Commands

7.docker network

Containers are isolated from containers and from host networks by default,

When you install Docker, Docker creates a bridge docker0, which allows containers to communicate with each other and with the host.

When Docker is installed, it creates three different networks by default, which you can view with commands.

docker network ls
Copy the code

#The following information is displayed after the help command[root@vultrguest ~]# docker network --help Usage: docker network COMMAND Manage networks Options: --help Print usage Commands: Connect Connects a container to a Docker network Create Creates a Docker LAN disconnect Disconnects a container from a LAN Inspect displays information about a LAN ls Displays all Docker LAN Prunes Rm Delete docker network rm delete Docker network Run 'docker network COMMAND --help' for more information on a COMMANDCopy the code

7.1. Default network

7.1.1. None of the Network

If the network mode is None, no network environment is created for the container.

Once a Docker Container uses None network mode, only loopback network devices are used inside the Container and no other network resources are available.

7.1.2. The Host Network

If you create a container with the **–network=host option, the container will use the host network **. The container is not isolated from the host network.

The advantage of using this type of network is that the network performance is very good, basically the same as the host network, but the big disadvantage is that it is not secure.

You can change the host network in the container, and if your application is running as root, it may use the Docker container to control the host network.

When we run a command like ifconfig in the container to view the network environment, all we see is information from the host.

7.1.3. Bridge Network

The bridge network is the default network type, and we can use the following command to view the default network configuration information.

The bridge network here is called Docker0. When we start a container, each container has its own virtual network interface connected to Docker0 and gets an IP address.

7.2. User-defined networks

7.2.1 Creating a Network

docker network create mynet
Copy the code

7.2.2. Add containers to the LAN

#Run the Redis container
docker run -itd --name redis  --network mynet --network-alias redis -p 6379:6379 redis
#Run the nginx container
docker run -d --name nginx -p 8081:8081 --network mynet --network-alias nginx --privileged=true   -v /home/wwwroot:/home/wwwroot -v /home/wwwlogs:/home/wwwlogs  nginx

Copy the code

7.2.3. View Mynet information

7.2.4. Docker network connect

You can also start the container without specifying a network and then connect to the network using Docker Network Connect

docker network connect mynet nginx
docker network connect mynet redis
Copy the code

7.2.5. Removing a LAN

docker network disconnect mynet nginx
Copy the code

8. The cluster