Docker virtualization technology

Long Tao 2020-11-10 11:31:10
docker virtualization technology


That's according to a B standing Meet the madman and say Docker Learning notes of

Need to learn Docker Technology

  • Docker summary

  • Docker install

  • Docker command

    • Mirror command
    • Container order
    • Operation command
  • Docker Mirror image

  • Docker Data volume

  • DockerFile

  • Docker Network principle

  • IDEA The integration of Docker

  • Docker Compose( colony )

  • Docker Swarm

  • CI\CD jenkins

matters needing attention :

stay win10 Install in docker When , Automatically enabled hyperV, but VMware Can't use HyperV Start virtual machine , Will cause the virtual machine to be unusable

resolvent :

  • When using Docker For Window, And don't use VMware when , Please use Administrator status function PowerShell, And enter the command :

    bcdedit /set hypervisorlaunchtype auto
    

    Then restart the computer ; here Docker For Window function Ok.

  • When you need to WMware Rather than using Docker For WIndow when , Please use Administrator status function PowerShell, And enter the command :

    bcdedit /set hypervisorlaunchtype off
    

    enter , Then restart the computer ; here WMware function Ok.

You have to restart your computer after each modification , So much trouble , I still use it directly in the virtual machine docker Well , ha-ha

Docker summary

Docker Why does it show up :

In order to solve “ Running on my computer is normal ” Other questions , Solve the problems of the program in different environments

Traditional deployment : Development jar package , Operation and maintenance to deploy

Now the deployment method : Development package deployment online , A set of processes can complete the whole deployment process

Docker Problem solved :

JRE: There may be port conflicts between multiple applications , Use Docker Ready to install (Tomcat、mysql The content such as )

Isolation :Docker The core idea of , Each box is isolated from each other

Essentially : All the technology is due to some problems , We need to solve before we can learn

virtual machine : Use virtual machine software on one computer to create multiple computers ; Virtual machine also belongs to virtualization technology , It's also a virtualization technology .

Containers : Isolation , Mirror image ( The core image is usually very small , It's usually 4M about )

Docker Is based on Go Language development ,

docker Official website :https://www.docker.com/

Docker Document address :https://docs.docker.com/

Docker Warehouse address :https://hub.docker.com/

Docker What can be done

Disadvantages of virtual machine :

  1. It takes up a lot of resources
  2. There are many redundant steps
  3. Slow start up

Containerization Technology : It's not a simulated whole operating system , It's about forming containers , Don't interfere with each other

Comparison of virtual machines and containers :

  • The traditional virtual machine simulates the whole hardware replacement , Then install and run the software on this system
  • The application of container content runs directly in the host , The container does not have its own kernel , It doesn't simulate hardware either , It takes up a small amount of resources
  • The containers are isolated from each other , Each container has its own file system , They don't influence each other

DevOps( Development 、 operating ): Faster delivery and deployment of applications

Docker: Package image release test , One click operation

More convenient upgrade and expansion

Simpler system operation and maintenance

After containerization , Our development , The test environment is highly consistent

More efficient use of computing resources

Docker It's kernel level virtualization , You can run multiple container instances on a single physical machine

Docker Installation

Docker Basic composition of

Mirror image (image):

docker Image is a template , Create a container service from this template , With this image, you can create multiple containers ( The final service run and the project run are both in the container )

Containers :

Docker Using container technology , Run an application or group of applications independently , Create by mirroring , A container can be understood as a compact version of a virtual machine system .

Warehouse :

The warehouse is the place to prevent the mirror image ,( It's like git The warehouse of )

Warehouses are also divided into public warehouses and private warehouses , The default warehouse is located abroad , Alibaba cloud container server can be used in China .

install Docker

Environmental preparation :

1、 need Linux Basics

2、 need Linux Environmental Science

install

  1. Uninstall the old version of Docker,Docker need centos Version above Linux kernel

     sudo yum remove docker \
    docker-client \
    docker-client-latest \
    docker-common \
    docker-latest \
    docker-latest-logrotate \
    docker-logrotate \
    docker-engine
    
  2. Install the software

    sudo yum install -y yum-utils
    
  3. Set up image warehouse

    # Foreign version of the warehouse image , It's very slow
    sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
    # Image of alicloud version , It's faster
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
  4. install Docker engine

    docker-ce : Community version docker-ee: Business Edition

    # Update to the latest version
    sudo yum makecache fast
    # install docker-ce
    sudo yum install docker-ce docker-ce-cli containerd.io
    # Or install the specified version of docker edition
    sudo yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io
    
  5. start-up docker

    systemctl start docker
    
    • Use docker version Look at specific docker Version information
    [root@centos-2 ~]# docker version
    Client: Docker Engine - Community
    Version: 19.03.12
    API version: 1.40
    Go version: go1.13.10
    Git commit: 48a66213fe
    Built: Mon Jun 22 15:46:54 2020
    OS/Arch: linux/amd64
    Experimental: false
    Server: Docker Engine - Community
    Engine:
    Version: 19.03.12
    API version: 1.40 (minimum version 1.12)
    Go version: go1.13.10
    Git commit: 48a66213fe
    Built: Mon Jun 22 15:45:28 2020
    OS/Arch: linux/amd64
    Experimental: false
    containerd:
    Version: 1.2.13
    GitCommit: 7ad184331fa3e55e52b890ea95e65ba581ae3429
    runc:
    Version: 1.0.0-rc10
    GitCommit: dc9208a3303feef5b3839f4323d9beb36df0a9dd
    docker-init:
    Version: 0.18.0
    GitCommit: fec3683
    
  6. function docker hello world

    First, determine whether the image exists , If it doesn't exist , So pull from the remote warehouse hello-world Warehouse

    # docker run hello-world
    

  1. View the downloaded image

    docker images
    

  1. uninstall docker Mirror image

    1. Uninstall the installed software
    2. Remove the installation directory
    sudo yum remove docker-ce docker-ce-cli containerd.io
    sudo rm -rf /var/lib/docker
    

Docker The underlying principle of

Docker How it works

Docker It's a client-server Institutional systems .Docker Is running on the host , adopt Socket Access from the client .

DockerServer Received Docker-Client Instructions , Will execute this instruction !

Docker Why faster than virtual machines ?

1、Docker There are fewer layers of abstraction than virtual machines

2、Docker Using the kernel of the host ,vm What is needed is Guest OS,

So , When you create a new container ,docker No need to reload an operating system kernel like a virtual machine , Avoid leading . Virtual machine loading Guest Os, The run time is minute level ;docker It's using the host's operating system , Ignoring this complex process , The running time is seconds .

Docker The basic order of

Help order

docker version # Show docker Version information for
docker info # Show docker System information , Including the number of mirrors and containers
docker --help # Help order

Mirror command

docker images

Use the help command to see all the images command

# docker images --help
Usage: docker images [OPTIONS] [REPOSITORY[:TAG]]
List images
Options:
-a, --all # List all the images
--digests Show digests
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print images using a Go template
--no-trunc Don't truncate output
-q, --quiet # Image only id
  1. docker images command

    # docker images
    REPOSITORY TAG IMAGE ID CREATED SIZE
    hello-world latest bf756fb1ae65 6 months ago 13.3kB
    ======================== Command interpretation =====================
    REPOSITORY: Image warehouse
    TAG: Mirrored label
    IMAGE ID: mirrored id
    CREATED: Image creation time
    SIZE: Size of the image
    
  2. docker search Search mirroring

    help List all the optional commands

    [root@centos-2 ~]# docker search --help
    Usage: docker search [OPTIONS] TERM
    Search the Docker Hub for images
    Options:
    -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
    

    lookup mysql

    [root@centos-2 ~]# docker search mysql
    NAME DESCRIPTION STARS OFFICIAL AUTOMATED
    mysql MySQL is a widely used, open-source relation… 9770 [OK]
    # optional , Filtering through collections
    docker search mysql --filter=STARS=3000 # You can search for stars Greater than 3000 The option to
    
  3. dockers pull

    help command

    [root@centos-2 ~]# docker pull --help
    Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST]
    Pull an image or a repository from a registry
    Options:
    -a, --all-tags Download all tagged images in the repository
    --disable-content-trust Skip image verification (default true)
    --platform string Set platform if server is multi-platform capable
    -q, --quiet Suppress verbose output
    

    download mysql Mirror image

    # Download mirroring :docker pull Mirror name [:tag]
    [root@centos-2 ~]# docker pull mysql
    Using default tag: latest # If you don't write tag, So download by default latest
    latest: Pulling from library/mysql #
    6ec8c9369e08: Pull complete # Layered download ,docker image At its core is the federated file system
    177e5de89054: Pull complete
    ab6ccb86eb40: Pull complete
    e1ee78841235: Pull complete
    09cd86ccee56: Pull complete
    78bea0594a44: Pull complete
    caf5f529ae89: Pull complete
    cf0fc09f046d: Pull complete
    4ccd5b05a8f6: Pull complete
    76d29d8de5d4: Pull complete
    8077a91f5d16: Pull complete
    922753e827ec: Waiting
    # Specify version information
    [root@centos-2 ~]# docker pull mysql:5.6 # The version number needs to be in docker The warehouse allows
    
  4. The delete command : docker rmi -f Mirror image id

    # Delete a single image
    docker rmi -f Mirror image id
    # Delete multiple images
    docker rmi -f Mirror image id Mirror image id Mirror image id
    docker rmi -f $(docker images -aq) # Delete all mirrors
    

Container order

explain : You can create containers with mirrors , Download a centos Mirror image as an exercise

docker pull centos

Create a new container and start

docker run [ Optional parameters ] image
# Optional parameters
--name Name Container name Tomcat01 etc.
--d Background operation
--it Run in interactive mode , Enter the container to view the contents
--p Specify container port -p 8080:8080
-ip: Host port : Container port
-p Host port : Container port ( Common ways )
-p Container port
-p Randomly assign ports

Start the host , The host name is the container id

[root@centos-2 ~]# docker run -it centos /bin/bash # This is a basic version , Many commands don't exist
[root@397571d3a5ef /]# exit # sign out

See the command to run the container :

docker ps
docker ps -a # Look at the programs that have run before

docker ps All commands :

[root@centos-2 ~]# docker ps --help
Usage: docker ps [OPTIONS]
List containers
Options:
-a, --all Show all containers (default shows just running)
-f, --filter filter Filter output based on conditions provided
--format string Pretty-print containers using a Go template
-n, --last int Show n last created containers (includes all states) (default -1)
-l, --latest Show the latest created container (includes all states)
--no-trunc Don't truncate output
-q, --quiet Only display numeric IDs
-s, --size Display total file sizes

Exit the container

exit # Stop the container and exit
ctrl + P + q # Exit the container without stopping

Delete container

docker rm Containers id # Delete a single image , Cannot delete a running container , If you need to force deletion rm -f
docker rm -f $(docker ps -aq) # Delete all that goes on
docker ps -a -q | xargs docker rm # Delete all containers

Start and stop the container

docker start Containers id # Start the container
docker restart Containers id # Restart the container
docker stop Containers id # Stop container
docker kill Containers id # Kill the container

Docker Other orders for

Background start container :

docker run -d Container name # Return to the container id
# Use docker ps Found the container stopped
# docker Run in the background , There must be a foreground process ,docker Found that no application will automatically stop ,
[root@centos-2 ~]# docker run -d centos /bin/sh -c "while true; do echo hello;sleep 1;done"
3b244f33c79dc16b9f8956405a7c3553df5f01141189bcf0d90228fa17d213bc

Check the log :

docker logs
# Use help
[root@centos-2 ~]# docker logs --help
Usage: docker logs [OPTIONS] CONTAINER
Fetch the logs of a container
Options:
--details Show extra details provided to logs
-f, --follow Follow log output
--since string Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
--tail string Number of lines to show from the end of the logs (default "all")
-t, --timestamps Show timestamps
--until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)

Check the log

docker logs -tf --tail 10 Containers id

Docker Process information

Show docker Process information in

[root@centos-2 ~]# docker top --help
Usage: docker top CONTAINER [ps OPTIONS]
Display the running processes of a container

Usage method :

docker top Containers id

Docker View container internal information

Look inside the container

[root@centos-2 ~]# docker inspect --help
Usage: docker inspect [OPTIONS] NAME|ID [NAME|ID...]
Return low-level information on Docker objects
Options:
-f, --format string Format the output using the given Go template
-s, --size Display total file sizes if the type is container
--type string Return JSON for specified type

Use command :

[root@centos-2 ~]# docker inspect 3b244f33c79d
[
{
"Id": "3b244f33c79dc16b9f8956405a7c3553df5f01141189bcf0d90228fa17d213bc",
"Created": "2020-07-27T23:14:11.789091289Z",
"Path": "/bin/sh",
"Args": [
"-c",
"while true; do echo hello;sleep 1;done"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
.....

The command to enter the currently running container

Containers are generally run in the background , You need to get into the container , Change some settings

[root@centos-2 ~]# docker exec --help
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Run a command in a running container
Options:
-d, --detach Detached mode: run command in the background
--detach-keys string Override the key sequence for detaching a container
-e, --env list Set environment variables
-i, --interactive Keep STDIN open even if not attached
--privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
-w, --workdir string Working directory inside the container

Before entering centos

[root@centos-2 ~]# docker exec -it 3b244f33c79d /bin/bash
[root@3b244f33c79d /]# # The name of the system can be seen here , Already in docker In the container

The second command to enter the container :attach

[root@centos-2 ~]# docker attach --help
Usage: docker attach [OPTIONS] CONTAINER
Attach local standard input, output, and error streams to a running container
Options:
--detach-keys string Override the key sequence for detaching a container
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)

and exec The difference is ,attach Enter the running command line , That is, printing hello The command line ;

exec A new command line has been opened

[root@centos-2 ~]# docker attach 1428eeb235f7
hello
hello
hello
.......

Docker Copy from the container to the host

[root@centos-2 ~]# docker cp --help
Usage: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Copy files/folders between a container and the local filesystem
Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.
Options:
-a, --archive Archive mode (copy all uid/gid information)
-L, --follow-link Always follow symbol link in SRC_PATH

First run the container , In the container /home New China 1.txt file , Back to the mainframe , Use ps View container's id( Whether the container is on or off , As long as you can get the container id, You can get the data ),

# The container /home/1.txt Copy to the host /home Under the table of contents
docker cp a7a9957c2027:/home/1.txt /home

Summary

Docker Command practice

1. install nginx

1. Search mirroring : docker search nginx
2. Install the image : docker pull nginx
3. Check if the download is successful : docker images
4. function nginx, And will the container 80 Port mapping to native port number 3344, -name Rename ;
docker run -d --name nginx01 -p 3344:80 nginx
5. test : curl localhost:3306

If you change the configuration file every time , All need to go inside the container ; You can use a mapping path , Modify the file in this mapping path , It's automatically modified inside the container ( Data volume technology )

2. install Tomcat

# 1. Search for Tomcat edition :
# Official use
docker run -it --rm tomcat:9.0
# The previous use is to stop the container and the container still exists , docker run -it --rm , Generally used to test , Delete when used up
#1, install Tomcat
docker pull tomcat:9.0
# start-up Tomcat Containers
docker run -d -p 3355:8080 --name tomcat01 tomcat
# Into the container
docker exec -it tomcat01 /bin/bash
# Problems found :1、Linux There are fewer orders , 2. No, webapps The content in
# as a result of : The default selection is the smallest image , Cut out the unnecessary parts , It is enough to ensure the minimum operating environment

Deploy Es+Kibana

es There are a lot of exposed ports , It's a lot of memory ,es In general, the data needs to be placed in a safe directory : mount

#
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2
# It takes up a lot of memory , Use docker stats see cpu The state of

Visualization tools

  • portainer

    docker run -d -p 8080:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
    

what portainer

Docker Graphical management tools for ! Provide a background panel for us to operate

-v It's the mount command , Mount the container to the host

Docker Mirror image principle

What is a mirror image

Image is a lightweight 、 Executable standalone package , It can be used to package software running environment and software developed based on running environment , She contains everything a piece of software needs , Including code 、 Runtime libraries 、 Environment and configuration files, etc .

All applications are packaged directly into docker Mirror image , You can just run !

How to get a mirror image :

  • Download from remote repository
  • Friends copy
  • Make your own one DockerFile file

Docker Image loading principle

UnionFs ( Federated file system )

The layers of files we see when we download them are this principle !

UnionFs ( Federated file system ):Union File system is a kind of layering 、 Lightweight and high performance file system , It supports the modification of the file as a submission to layer by layer , At the same time, you can mount different directories to the same virtual file system .Union The file system is Docker The foundation of the mirror . Images can be inherited by layering , Based on the basic image ( Parentless mirror image ), It can be used to create images of various specific applications .

characteristic : Loading multiple file systems at once , But it looks like from the outside , Only one file system can be seen , The federated load will stack all layers of file systems , So the final file system will contain all the underlying files and directories .

Docker Image loading principle

docker The mirror image is actually composed of layers of file systems , This kind of hierarchical file system UnionFs.

bootfs(boot file system) It mainly includes BootLoader and kernel, BootLoader Mainly boot loading kernel,Linux It will load when it starts bootfs file system .docker The bottom of the mirror is bootfs. This layer is similar to our classic Linux/Unix The system is the same , contain boot Loader and kernel . When boot After loading, the whole kernel is in memory , At this time, the right to use the memory has been bootfs Transferred to the kernel , At this time, the system will also uninstall bootfs.

rootfs(root file system), stay bootfs above , Typical of contained Linux In the file system /dev /prpc /bin /etc Such as the standard directory and file .rootfs It's the distribution of different operating systems , for example Ubuntu and centos etc.

docker The system installed in is a compact os,rootfs It can be very small , Just include the basic commands , Tools and libraries will do , Because the bottom uses HOST Of kernel, I just need to provide rootfs That's all right. . This shows that for different Linux Distribution version ,rootfs They are basically the same . So different distributions can be shared bootfs.

Layering principle

When we download images , Found that the image is layered download

understand :

be-all docker Mirrors have a basic mirror layer , When changes or new content will be added , A new mirror layer will be created on the current image . For example, using Ubuntu Create a mirror image , On the first layer of the new mirror ; If you add Python package , A second mirror layer will be created on top of the base mirror layer ; If you continue to add security patches , It's going to create the 3 A mirror layer .

While adding extra mirror layers , Race is always a collection of all the current images , For example, the example in the figure below , The bottom layer of each image contains 3 File , And the mirror contains the 6 File

If it is in the underlying image, there are always files that need to be updated , Add the updated files directly to the mirror layer , In this way, it seems that the total number of files remains unchanged , For example, the file above 5 There is an update to the file 7, file 7 Located at 3 Layer mirror layer , But on the outside , This image is still 6 File

Docker Through the storage engine ( The new version uses snapshot mechanism ) Method to implement the mirror layer stack , And ensure that the multi mirror layer is displayed as a unified file system .

Linux The storage engines available on are AFUS、Overlay2、 Device Mapper、 Btrfs as well as ZFS. seeing the name of a thing one thinks of its function , Every storage engine is based on Linux File system or block device technology , And each storage structure has its own unique performance characteristics .

Docker stay Window Only supported on windowsfilter A storage engine , The engine is based on NTFS The file system is layered and Cow.

The following is the same as the system display 3 Layer mirror . All the mirror layers are stacked and merged , Show a unified view to the outside world

characteristic

Docker Images are read-only , When the container starts , A new writable layer is loaded onto the top of the mirror ! This layer is what we usually call the container layer , It's called the mirror layer under the container .

Commit Mirror image

docker commit Submit a container to become a new copy
docker commit -m " Description information submitted " -a “ author ” Containers id Target image name :[tag]

Container data volume

What is a container data volume

data : If the data is all in the container , If we delete the container , Then the data will be deleted ! demand : Data can be persistent

There can be a data sharing technology between containers ,Docker Data generated in the container , Sync to local . This is volume technology , Directory mount , Mount the directory in our container to Linux above .

summary : Persistence and synchronization of containers , Data can also be shared between containers

Using volume technology

Method 1 : Use the command to mount :-v

docker run -it -v Host Directory : In-container directory

take centos Inside the container /home The directory is mounted to the host /home/test Below directory

docker run -it -v /home/test:/home centos /bin/bash

Use docker inspect Look inside the container :

The folder in the container will be synchronized with the host's folder . Synchronization is a two-way process .

actual combat :Mysql Data synchronization

mysql The problem of persistence ;

step :

# 1. Search for mysql
docker search mysql
# 2. install mysql
docker pull mysql:5.7
# 3. start-up mysql, The configuration file and data file are mapped to the host at startup , And use -e To configure mysql Password
docker run -d -p 3310:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 --name mysql01 mysql:5.7

Mount with name and mount with anonymity

Mount anonymously :

-v In-container directory
docker run -d -P --name nginx01 -v /etc/nignx nginx
# docker volume Command view docker Data volume in
[root@centos-2 test]# docker volume --help
Usage: docker volume COMMAND
Manage volumes
Commands:
create Create a volume
inspect Display detailed information on one or more volumes
ls List volumes
prune Remove all unused local volumes
rm Remove one or more volumes
Run 'docker volume COMMAND --help' for more information on a command.
# View all volume The situation of
[root@centos-2 test]# docker volume ls
DRIVER VOLUME NAME
local f32fb32afe3ffa1b3c691af07adc7b244ae225142f44849316bef56e0f69b826
# Here we find , This is anonymous mount , -v I only wrote the name inside the container, not the name outside the container

Mount with a name :( Frequently used )

Is in the -v Volume name : Container path

docker run -d -P --name nginx03 -v nignx-config:/etc/nignx nginx

If no absolute path is specified , Then it will be in /var/lib/docker/volumes in

# Use the command to view the path of the volume mount
[root@centos-2 test]# docker volume inspect nignx-config
[
{
"CreatedAt": "2020-07-28T13:32:36+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/nignx-config/_data",
"Name": "nignx-config",
"Options": null,
"Scope": "local"
}
]
# You can see nignx-config The file is mapped to /var/lib/docker/volumes/ Under the table of contents

How to distinguish between named mount and anonymous mount

-v Container path # Mount anonymously
-v Volume name : Container path # Mount with a name
-v / Host path : Container path # Host mount

expand

# adopt -v Container path ,ro,rw Change read and write permissions
ro readonly # read-only , This path can only be operated by the host , The inside of the container is not operational
rw readwrite # read-write
# Once the permissions for the container are set , The container limits what we mount
docker run -d -P --name nginx03 -v nignx-config:/etc/nignx:rw nginx
docker run -d -P --name nginx03 -v nignx-config:/etc/nignx:ro nginx

DockerFile

First time to know DockerFile

DockerFile It's used to build docker The build file for the image . It's a command script

stay home Create a new one in the directory docker-file-test Folder , Create a file in the folder dockerfile1 write in :

# Contents of the document , The instructions should be capitalized , Every command here is a layer of mirror image
FROM centos
VOLUME ["volume01", "volume02"]
CMD echo "-----end-----"
CMD /bin/bash

And then execute the command

docker build -f ./dockerfile1 -t lt/centos:0.1 .
[root@centos-2 docker-file-test]# docker build -f ./dockerfile1 -t lt/centos:0.1 .
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM centos
---> 831691599b88
Step 2/4 : VOLUME ["volume01", "volume02"]
---> Running in e7e474ee96b4
Removing intermediate container e7e474ee96b4
---> d1ff35b3eb7a
Step 3/4 : CMD echo "-----end-----"
---> Running in 1717e5164a2f
Removing intermediate container 1717e5164a2f
---> 83d12f6470b9
Step 4/4 : CMD /bin/bash
---> Running in 2952add39b0f
Removing intermediate container 2952add39b0f
---> 229f3e861101
Successfully built 229f3e861101
Successfully tagged lt/centos:0.1
# Check whether to generate images, Discovery has generated image
[root@centos-2 docker-file-test]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
lt/centos 0.1 229f3e861101 20 seconds ago 215MB

Start your own mirror image

docker run -it 229f3e861101 /bin/bash

This volume must correspond to a directory in the host , And these two volumes are mounted anonymously

# Use docker inspect See the details of the container
[root@centos-2 test]# docker inspect 09714e560694 # Containers id

We will use this method a lot in the future , Because we will build our own mirror image ,

Suppose there is no mounted volume when building the image , You need to mount it manually -v Volume name : Container path

Data volume container

Multiple mysql Implement data sharing

# Parent container
docker run -it --name docker01 Image name
# Subclass
docker run -it --name docker02 --volumes-from docker01 Image name
# In this way, the subclass inherits the parent container , Data volume container synchronization .
# If you delete docker01, The view file still exists , Files are a way to copy two-way

Conclusion :

Configuration between containers to transfer messages , The life cycle of a data volume lasts until there is no container in use , But once it's persisted locally , Local data is not deleted .

DockerFile structure

Basic knowledge of :

  1. Each reserved keyword must be uppercase

  2. Instructions are executed from top to bottom

  3. # Notation

  4. Each assignment creates and submits a new mirror layer

dockerfile Facing the development of , We're going to release the project later , Mirror image , I'm going to write dockerfile file , This document is very simple !

DockerFile: Build file , Defines all the steps , Source code

DockerImages: adopt DockerFile Build and generate images , Finally release and run the product

Docker Containers : A container is an image that runs to provide a server .

DockerFile Instructions

FROM # base image , It's all built from here
MAINTAINER # Who wrote the mirror image full name + mailbox
RUN # The command to run when the image is built
ADD # step :Tomcat Mirror image , This Tomcat Compressed package ! Add content
WORKDIR # The working directory of the mirror image
VOLUME # Mount Directory
EXPOSE # Exposed port
CMD # Specifies the command to run when the container is running ; Only the last one works , Can be replaced by
ENTERYPOINT # Specifies the command to start when this container is started , You can add
ONBUILD # When building an inherited DockerFile This time it will run ONBUILD Instructions , Trigger command
COPY # Be similar to ADD, Copy our files into the image
ENV # Set environment variables when building

Actual test :

Docker Hub The images in are all from The basic mirror image of FROM scratch, Then configure other software

Create your own Centos

FROM centos
MAINTAINER longtao<longtao55@163.com>
ENV MYPATH /usr/local
WORKDIR $MYPATH
RUN yum install -y vim
RUN yum install -y net-tools
EXPOSE 80
CMD echo %MYPATH
CMD echo "====end====="
CMD /bin/bash

Building images from files

docker build -f mydockerfile -t mycentos:0.1 .

We can list the change history of the local image

docker history Mirror image id

DockerFile Create a tomcat

  1. Prepare the image file Tomcat Compressed package , jdk Compressed package

  2. To write DockerFile file Official name Docker,build It will automatically search for this file , No need to use -f Appoint

    FROM centos
    MAINTAINER longtao<longtao55@163.com>
    COPY readme /usr/local/readme
    ADD apache-tomcat-9.0.37.tar.gz /usr/local
    ADD jdk-8u261-linux-x64.tar.gz /usr/local
    ENV MYPATH /usr/local
    WORKDIR $MYPATH
    ENV JAVA_HOME /usr/local/jdk1.8.0_261
    ENV CLASSPATH $JAVA_HOME/lib
    ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.37
    ENV CATALINA_BASH /usr/local/apache-tomcat-9.0.37
    ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
    EXPOSE 8080
    CMD /usr/local/apache-tomcat-9.0.37/bin/startup.sh && tail -f /usr/local/apache-tomcat-9.0.37/logs/catalina.out
    
  3. Build a mirror image

    docker build -t mytomcat
    
  4. Start the mirror

  5. The test image

  6. Publish the project

Release image

DockerHub

  1. Registered account

  2. Make sure this account can log in

    docker login -u user name -p password
    
  3. After login, you can use docker push Send the image to docker Hub in

  4. If the display does not have a local version , You can use tag Change the label

Docker The Internet

understand Docker0 The Internet

see docker Inside ip Address

docker exec -it tomcat ip addr

principle

  1. Every time we start one docker Containers ,docker Will give you docker The container allocates a ip, We just need to install docker, There will be a network card docker0 Bridging mode , The technology used is evth-pair technology !

  2. Start a container again , Found another network card

    # We found that this container brought the network card , It's all one-on-one
    # evth-pair It's a pair of network device interfaces , They all appear in pairs , A link to the protocol , A segment is connected to each other
    # This is because of this feature ,evth-pair Act as a container , Connected to a variety of virtual devices
    # OpenStack、Docker Connections between containers OVS Connect Is to use evth-pair technology
    
  3. docker Containers can be mutual ping through

Conclusion :Tomcat01 and Tomcat02 It's sharing a router docker0;

In all cases, the network container is not specified , All are docker0 Router ,docker Our container will be assigned a default available ip

Docker The network is virtual , Virtual forwarding is efficient !( Transfer files on Intranet )

Just delete the container , The corresponding bridge disappears .

Project does not restart , data ip Replaced , We hope to be able to deal with this problem , The container can be accessed by name ?

For example, in Tomcat01 in ping Tomcat02, But I don't know Tomcat02 Of ip Address , So you can use --link As a way :

docker run -d -P --name tomcat01 --link tomcat02 tomcat
docker exec -it tomcat01 ping tomcat02 # Right now ping Through the
# In reverse ping It may not work

--link Is that we are host A new configuration has been added Tomcat02 Information about

Custom network

[root@centos-2 ~]# docker network --help
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks
rm Remove one or more networks
Run 'docker network COMMAND --help' for more information on a command.

View all docker The Internet

Network mode :

bridge: Bridging mode , stay docker Build a network bridge on

none: No network configuration

host: Host mode , Share the network with the host

container: Container network connectivity ( Rarely used , It's very limited )

test

In the container we started earlier , The default mode is --net bridge

docker run -it -P --name tomcat01 --net bridge tomcat

docker0 Characteristics , Default , Domain name cannot be accessed ,

Create your own network

docker network create --driver bridge --subnet 192.168.0.0/16 --gateway 192.168.0.1 mynet

Self created networks can be accessed without using names , Self defined docker Have helped us maintain the corresponding relationship , It is recommended to use such a network .

Network interconnection

# The container connects to the network
docker network connect mynet tomcat01
# take Tomcat01 Put in mynet In the network , One container, two ip

actual combat : Deploy Redis colony

step :

  1. Creating networks

    docker network create --subnet 172.38.0.0/16 redis
    
版权声明
本文为[Long Tao]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云