Beginner docker container

What is docker

  • docker is a lightweight virtual machine
  • Running applications in linux container and open source

The difference between docker and virtual machine

differencecontainervirtual machine
Starting speedSecond orderMinute level
Operation performanceNear native (90% running directly in the kernel)About 50% loss
quantityDepending on the process, there can be many hundreds of processesGeneral dozens (operating system level)
quarantineProcess levelSystem level (more thorough isolation)
Disk occupancyMBG B (the image of the operating system is generally about several gigabytes)
operating systemIt mainly supports linuxAlmost all systems
Encapsulation degreeOnly package the project code and dependencies, and share the host kernelComplete operating system, isolated from the host

At the same time, docker solves the environment island problem of vm, and docker can customize the transfer parameters

docker usage scenario

  • Used to package applications and simplify deployment
  • Any migration away from the underlying hardware
  • Continuous integration and continuous delivery (CI/CD): development to test release
  • Deploy microservices
  • Provide PAAS products

Principle of docker

cgroup resource control and namespace namespace combine to control and manage six namespace resources to achieve complete isolation / complete isolation

  • Mount: file system, mount point
  • User: the user and user group of the operation process
  • pid: process number
  • uts: host name and host domain
  • ipc: semaphore, message queue, shared memory (different applications use different memory space when calling memory resources)
  • net: network equipment, network protocol stack, port, etc
    The mount namespace: manages file system mount points
    This pid namespace: process isolation (pid: process id)
    The uts namespace: isolated kernel and version identifier (uts: Unix time sharing system)
    This ipc namespace: manages access to ipc resources (ipc: communication between processes)
    The net namespace: management network interface (net: Network)

Three unifications of docker and three components of docker

docker makes container technology into a standardized platform

  • Docker engine unifies the infrastructure environment - docker environment
  • Docker engine unifies the program packaging method - docker image
  • Docker engine unifies the program deployment method - "docker container" - based on image, running as a container (runnable environment)
    It realizes one-time construction, multiple times and multiple uses
    Three components:
  • Image: as a template, a collection of resources, including application software packages, application related dependency packages, and the basic environment required to run applications
  • Container: running state / runtime state, a runtime state based on image
  • Warehouse: the place where image templates are stored. Warehouse classification: public warehouse – docker hub, private warehouse – registry harbor

docker engine

The docker engine is a C/S application (client server) with the following main components
Server side: the server is a long-running program and becomes a daemon
client side: REST API specifies the interface that the program can use to communicate with the daemon and indicate its operation

Docker server configuration file

Configure in / etc/docker/daemon.json

{
"graph":"/data/docker",			//Data directory
"storage-driver":"overlay2",		//Storage engine
"insecure-registries" ["registry.access.redhat.com","quary.io"]	//Private warehouse
"registry-mirrors": ["https://cn90fxk6.mirror.aliyuncs.com"] 	// Image acceleration
"bip":"172.17.0.1/24",			//docker network
"exec-opts":["native.cgroupdriver=systemd"],		//Additional parameters at startup
"live-restore":true			//When the docker container storage engine hangs, the container running with docker can still run
}

Deployment of docker (version 20)

  • Install dependent packages
[root@node1 nginx]# yum install -y yum-utils device-mapper-persistent-data lvm2

  • Set alicloud image source
[root@node1 yum.repos.d]# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

  • Install docker CE Community Edition
[root@node1 yum.repos.d]# yum install -y docker-ce

  • Then start docker
[root@node1 yum.repos.d]# systemctl enable docker
[root@node1 yum.repos.d]# systemctl start docker

  • Set image acceleration to Alibaba cloud's image acceleration classification

  • Just copy the following code directly to the command line, and select the corresponding operating system

  • Check whether the setting is successful

[root@node1 yum.repos.d]# vim /etc/docker/daemon.json 
{
  "registry-mirrors": ["https://cn90fxk6.mirror.aliyuncs.com"]
}

docker image operation

[root@node1 yum.repos.d]# docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.		//The client is connected to the server
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.			//The server daemon downloads the image from the docker hub
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.		//The server creates a new container, then starts a container from the image, and the container executes the script
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.		//The server returns these information streams to the client for display

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

  • Query docker version
[root@node1 yum.repos.d]# docker version 
Client: Docker Engine - Community
 Version:           20.10.8
 API version:       1.41
 Go version:        go1.16.6
 Git commit:        3967b7d
 Built:             Fri Jul 30 19:55:49 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.8
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.6
  Git commit:       75249d8
  Built:            Fri Jul 30 19:54:13 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.9
  GitCommit:        e25210fe30a0a703442421b0f60afac609f950a3
 runc:
  Version:          1.0.1
  GitCommit:        v1.0.1-0-g4144b63
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

[root@node1 yum.repos.d]# docker info 
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.6.1-docker)
  scan: Docker Scan (Docker Inc., v0.8.0)

Server:
 Containers: 14
  Running: 5
  Paused: 0
  Stopped: 9
 Images: 63
 Server Version: 20.10.8
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: e25210fe30a0a703442421b0f60afac609f950a3
 runc version: v1.0.1-0-g4144b63
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-957.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 5.712GiB
 Name: node1
 ID: QL6Y:HC6L:E57G:UWHJ:E7FY:J47A:YF6Z:GLL2:DETH:DY4C:STNH:ZGFS
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Registry Mirrors:
  https://cn90fxk6.mirror.aliyuncs.com/
 Live Restore Enabled: false

WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled

  • Search image
[root@node1 yum.repos.d]# docker search nginx
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
nginx                             Official build of Nginx.                        15420     [OK]       
jwilder/nginx-proxy               Automated Nginx reverse proxy for docker con...   2063                 [OK]
richarvey/nginx-php-fpm           Container running Nginx + PHP-FPM capable of...   816                  [OK]
jc21/nginx-proxy-manager          Docker container for managing Nginx proxy ho...   240                  
linuxserver/nginx                 An Nginx container, brought to you by LinuxS...   152                  
tiangolo/nginx-rtmp               Docker image with Nginx using the nginx-rtmp...   141                  [OK]
jlesage/nginx-proxy-manager       Docker container for Nginx Proxy Manager        135                  [OK]
alfg/nginx-rtmp                   NGINX, nginx-rtmp-module and FFmpeg from sou...   106                  [OK]
jasonrivers/nginx-rtmp            Docker images to host RTMP streams using NGI...   92                   [OK]
nginxdemos/hello                  NGINX webserver that serves a simple page co...   72                   [OK]
privatebin/nginx-fpm-alpine       PrivateBin running on an Nginx, php-fpm & Al...   56                   [OK]
nginx/nginx-ingress               NGINX and  NGINX Plus Ingress Controllers fo...   55                   
nginxinc/nginx-unprivileged       Unprivileged NGINX Dockerfiles                  47                   
staticfloat/nginx-certbot         Opinionated setup for automatic TLS certs lo...   24                   [OK]
nginxproxy/nginx-proxy            Automated Nginx reverse proxy for docker con...   20                   
schmunk42/nginx-redirect          A very simple container to redirect HTTP tra...   19                   [OK]
nginx/nginx-prometheus-exporter   NGINX Prometheus Exporter for NGINX and NGIN...   19                   
centos/nginx-112-centos7          Platform for running nginx 1.12 or building ...   15                   
centos/nginx-18-centos7           Platform for running nginx 1.8 or building n...   13                   
bitwarden/nginx                   The Bitwarden nginx web server acting as a r...   11                   
flashspys/nginx-static            Super Lightweight Nginx Image                   10                   [OK]
mailu/nginx                       Mailu nginx frontend                            9                    [OK]
sophos/nginx-vts-exporter         Simple server that scrapes Nginx vts stats a...   7                    [OK]
ansibleplaybookbundle/nginx-apb   An APB to deploy NGINX                          2                    [OK]
wodby/nginx                       Generic nginx                                   1     
[root@node1 yum.repos.d]# docker search centos:7
NAME                                                DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
benwang6/tedu-jdk                                   oracle jdk 8u281 centos:7 JAVA_HOME=/usr/jdk...   5                    
vikingco/python                                     Python Stack Docker Base Image: Based on cen...   1                    
sndnvaps/docker-golang                              build latest golang in centos:7                 1                    [OK]
legerete/nginx-php71                                LA[->]P - Centos:7 + Nginx + PHP 7.1            1                    [OK]
peltikalle/basepython                               Base image with Centos:7 and Python 3.5.2       1                    [OK]
mjstealey/mariadb-galera                            MariaDB Galera cluster in Docker - based fro...   1                    [OK]
acktsw/java                                         oracle jdk 8u171 , centos:7,  timeZone:+8, e...   0                    [OK]
macedigital/nodejs                                  Latest NodeJS for CentOS:7                      0                    [OK]
grossws/nginx                                       nginx (mainline) on grossws/centos:7            0                    [OK]
europeanspallationsource/oracle-jdk-maven-jenkins   ICS oracle-jdk + maven + jenkins users image...   0                    
pbieberstein/acic-findr                             CentOS:7 with dependencies to run 'Findr' (h...   0                    [OK]
sjoeboo/rbenv                                       Simple base container from CentOS:7 w/ rbenv...   0                    [OK]
alvintz/centos                                      centos:7.2.1511                                 0                    [OK]
geomatikk/centos                                    FROM centos:7 with maven 3.6.1 and openjdk-1...   0                    
waffleimage/centos7                                 Centos:7 with systemd and ssh running           0                    
cristo/netacuity                                    Docker image on Centos:7 to run NetAcuity       0                    [OK]
badwolf/centos                                      from official centos:7 add gcc,gcc++,make,vi    0                    [OK]
mesosphere/freeipa-server                           A freeIPA v4.3 container based on centos:7. ...   0                    
acktsw/centos                                       centos:7                                        0                    [OK]
bbania/centos                                       Build image based on centos:7                   0                    
a2747/centos7                                       derivative images from centos:7                 0                    
21plus2/server-jre                                  Dockerimage base on centos:7 with server-jre    0                    [OK]
europeanspallationsource/oracle-jdk-maven           ICS oracle-jdk + maven image based on centos...   0                    
qiyue/mycat                                         centos:7 + jdk:1.8 + mycat                      0                    
weihoop/mysql                                       be based on weihoop/centos:7.4.1708 make          
  • Download Image
[root@node1 yum.repos.d]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
a330b6cecb98: Pull complete 
5ef80e6f29b5: Pull complete 
f699b0db74e3: Pull complete 
0f701a34c55e: Pull complete 
3229dce7b89c: Pull complete 
ddb78cb2d047: Pull complete 
Digest: sha256:a05b0cdd4fc1be3b224ba9662ebdf98fe44c09c0c9215b45f84344c12867002e
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@node1 yum.repos.d]# docker images 			// View mirror list
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • Get image information
[root@node1 yum.repos.d]# docker inspect 822b7ec2aaf2
[
    {
        "Id": "sha256:822b7ec2aaf2122b8f80f9c7f45ca62ea3379bf33af4e042b67aafbf6eac1941",
        "RepoTags": [
            "nginx:latest"
        ],
        "RepoDigests": [
            "nginx@sha256:a05b0cdd4fc1be3b224ba9662ebdf98fe44c09c0c9215b45f84344c12867002e"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2021-09-03T07:40:16.355730864Z",
        "Container": "367d32086ac12447d36e75c9b7acbe1b5156a34a91370b9200e68783be75506c",
        "ContainerConfig": {
            "Hostname": "367d32086ac1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.21.1",
                "NJS_VERSION=0.6.1",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"nginx\" \"-g\" \"daemon off;\"]"
            ],
            "Image": "sha256:d4315787e4fec867791beba140dd0e44f657cb6e4a9d75c676c7946089c20da9",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],

  • Add mirror label
[root@node1 yum.repos.d]# docker images 
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         123       822b7ec2aaf2   2 days ago     133MB
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • delete mirror
[root@node1 yum.repos.d]# docker rmi nginx:123
Untagged: nginx:123
[root@node1 yum.repos.d]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • Export mirror
[root@node1 ~]# docker save -o nginx_images nginx:latest 
[root@node1 ~]# ls
12   1.sh   2333  45               apps         initial-setup-ks.cfg       ks.cfg  nginx_images  Template picture download desktop
123  1.txt  234   anaconda-ks.cfg  docker_home  jdk-8u91-linux-x64.tar.gz  nginx   public          Video document music

  • To import an image, delete the original image before importing it
[root@node1 ~]# docker load < nginx_images 
d000633a5681: Loading layer [==================================================>]  72.53MB/72.53MB
63b5f2c0d071: Loading layer [==================================================>]  64.86MB/64.86MB
875b5b50454b: Loading layer [==================================================>]  3.072kB/3.072kB
ed94af62a494: Loading layer [==================================================>]  4.096kB/4.096kB
8e58314e4a4f: Loading layer [==================================================>]  3.584kB/3.584kB
d47e4d19ddec: Loading layer [==================================================>]  7.168kB/7.168kB
Loaded image: nginx:latest
[root@node1 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
nginx         latest    822b7ec2aaf2   2 days ago     133MB

  • Query container
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS       PORTS                                         NAMES

  • Create container
[root@node1 ~]# docker create -it nginx:latest /bin/bash
9eade02412f5ecc3e9e2006de2f59845ca50ed4a52741ad9f0a8fb43ce5086f3
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS       PORTS                                         NAMES
9eade02412f5   nginx:latest   "/docker-entrypoint...."   3 seconds ago   Created                                                    keen_chatterjee
//-i is to keep the standard input of the container open
//-t is to assign a pseudo terminal
//-d is the way the background daemon runs
  • Start container
[root@node1 ~]# docker start 9eade02412f5
9eade02412f5
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS         PORTS                                         NAMES
9eade02412f5   nginx:latest   "/docker-entrypoint...."   About a minute ago   Up 2 seconds   80/tcp                                        keen_chatterjee

  • Execute once to start the container
[root@node1 ~]# docker run centos:7 /usr/bin/bash -c ls /
anaconda-post.log
bin
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var

  • Stop container
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS                       PORTS                                         NAMES
9eade02412f5   nginx:latest   "/docker-entrypoint...."   4 minutes ago    Exited (137) 6 seconds ago         		//All non-0 status values are stop status, and 137 is the index keen of stop command_ chatterjee

  • You can enter the container in both ways, but exec can only enter when the container is running
[root@node1 ~]# docker run -it nginx:latest /bin/bash
root@d36a26b3e1d2:/#
[root@node1 ~]# docker exec -it 9eade02412f5 /bin/bash
root@9eade02412f5:/# 
docker run -it The foreground process will be created, but it will be entered exit Terminate process after
docker exec -it Will be connected to the container, which can be like ssh Enter the container and operate through exit sign out
  • Container export
[root@node1 ~]# docker export 9eade02412f5 > nginx_1
[root@node1 ~]# ls
12   1.sh   2333  45               apps         initial-setup-ks.cfg       ks.cfg  nginx_1       Public video document music

  • Container import (generate mirror)
[root@node1 ~]# cat nginx_1 | docker import - nginx:latest
sha256:ae834c84afd17bb12708bd2dd4d53e8432c43d6378d0ed405e1fd580dd6f77ad

  • Delete container
[root@node1 ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS                     PORTS                                         NAMES
95b40e409895   nginx:latest   "/bin/bash"              9 seconds ago   Exited (0) 4 seconds ago                                                 sad_heyrovsky
[root@node1 ~]# docker rm 95b40e409895
95b40e409895
 Forced deletion of a running container can be added-f
  • Batch delete container
[root@node1 ~]# docker ps -a | awk '{print "docker rm "$1}' | bash
3e0845eacc5c
5e0ecd151d57
b8da82b16ba7
2930dd871f01
668103e78d6c
 perhaps
[root@node1 ~]# docker rm `docker ps -qa`

Keywords: Linux Operation & Maintenance Docker

Added by newbeee on Mon, 06 Sep 2021 01:40:53 +0300