Docker entry basic command

Article catalog

1, Overview

1. What is Docker

docker is an open source application container engine, which is developed based on go language and follows the Apache 2.0 protocol.

docker allows developers to package their applications and dependencies into a lightweight, portable container, and then publish them to any popular linux server. It also enables virtualization.

Containers use sandbox mechanism completely, there is no interface (iphone like app) between them, and the container overhead is extremely low.

2. Differences between container technology and virtual machine technology

  1. Virtual machine is a solution with environment installation.

    It can run another operating system in one operating system, such as Linux in Windows. The application is as like as two peas, because the virtual machine looks exactly the same as the real system. For the underlying system, the virtual machine is a common file, which is deleted without any need and has no effect on the other parts. This kind of virtual machine runs another system perfectly, which can make the logic among application, operating system and hardware unchanged.

    The disadvantages of virtual machine: more resources, more redundant steps, slow start-up.

  2. Due to these shortcomings of the previous virtual machines, Linux has developed another virtualization technology: Linux Containers (LXC).

    The Linux container does not simulate a complete operating system, but isolates processes. With containers, you can package all the resources needed for the software to run into an isolated container. Unlike virtual machines, containers do not need to be bundled with a whole set of operating systems, but only need the library resources and settings required by the software. As a result, the system becomes efficient and lightweight and ensures that the software deployed in any environment can run consistently.

The differences between container technology and virtual machine technology are compared

  1. In the traditional virtual machine technology, after a set of hardware is virtualized, a complete operating system is run on it, and then the required application process is run on the system.

  2. The application process in the container runs directly in the host kernel. There is no kernel in the container, and there is no hardware virtualization. So the container is lighter than the traditional virtual machine.

  3. Each container is isolated from each other. Each container has its own file system. Processes between containers will not affect each other, and computing resources can be distinguished.

3. Advantages of docker

Official words:

  • Flexibility: even the most complex applications can be containerized.
  • Lightweight: containers leverage and share the host kernel.
  • Interchangeable: you can deploy updates and upgrades instantly.
  • Portable: you can build locally, deploy to the cloud, and run anywhere.
  • Scalable: you can add and automatically distribute container copies.
  • Stackable: you can stack services vertically and instantly.

4. Docker architecture

  1. Client: interact with the Docker server through some commands, such as docker build: build a container; docker pull: pick up a container; docker run: run a container

  2. Docker_host (server): all docker operations are performed here

    1. Docker daemon: the principal part of docker architecture

      1. Provide the function of Server to accept the request of Docker Client
      2. When a container image is required, download the image from the Registry
    2. Images: the docker image is like a template, through which container services can be created. Through this image, multiple containers can be created (the final service running or project running is in the container).

    3. Containers: Docker uses container technology to independently run one or a group application and create it through image. (beginners can temporarily understand this container as a simple linux)

      The image can be understood as a class in java, while the container can be understood as an object instance in java. A class can have multiple object instances

  3. Register (remote warehouse): the place where the image is stored, divided into public warehouse and private warehouse

2, Install Docker

This part can refer to official documents: , install according to my own system. The system I use here is Centos 7

Install Docker on Centos system. This part is in the official document location (other Linux distribution installation methods are also here):

1. When the server has network

  1. Uninstall old version

    yum remove docker \
                      docker-client \
                      docker-client-latest \
                      docker-common \
                      docker-latest \
                      docker-latest-logrotate \
                      docker-logrotate \
  2. Required installation package

    yum install -y yum-utils
  3. Setting up the repository

    # Official code, the repository is foreign, slow to download
    yum-config-manager \
        --add-repo \
    # Alibaba cloud's image warehouse is recommended
    yum-config-manager \
        --add-repo \
  4. Install Docker engine
    Docker ce: ce refers to community version, and ee refers to enterprise version

    # Package index can be updated before installation (not required)
    yum makecache fast
    # Install the latest version of docker engine, including docker Community Edition, docker Community Edition client, etc
    yum install docker-ce docker-ce-cli
  5. Start Docker

    systemctl start docker
  6. Test whether Docker is installed successfully

    # View Docker version number
    docker version

    The following figure shows the successful installation:

  7. Test and download Hello world image

    docker run hello-world

  8. View the downloaded Hello world image

    docker images
  9. Uninstall Docker

    # Uninstall Docker Engine, CLI, etc
    yum remove docker-ce docker-ce-cli
    # The image, container, and other files on the host will not be deleted automatically, but need to be deleted manually
    # /Default working path of var/lib/docker docker
    rm -rf /var/lib/docker

2. Configure Alibaba cloud image acceleration

  1. Log in to alicloud( ), found container image service:
  2. If not, follow Alibaba cloud's steps.
  3. Find the lowest image accelerator, choose your own corresponding system, and follow the steps step by step

3. When the server has no network

This part can refer to official documents: Install Docker Engine from binary

The following installation process is performed on RHEL 7.3 system

  1. Install dependency package:

    yum install -y yum-utils device-mapper-persistent-data lvm2
  2. To view the schema of your own server:

    uname -a

    My is x86 64 bit:

  3. Then download the binary installation file compression package of docker. Address:

    According to the architecture found in step 2, select the compression package under the corresponding architecture, and choose the version by yourself. What I download here is: x86_64/docker-19.03.9.tgz

  4. Copy the compressed package to the machine and extract it:

    tar xzvf docker-19.03.9.tgz
  5. Copy the extracted file to the directory / usr/bin /

    cp docker/* /usr/bin/
  6. To start the Docker daemons:

    dockerd &
  7. Test whether docker is installed successfully: docker version

    The installation is successful as follows:

Three. Docker common commands

Official document: all commands of Docker:

1. View information

1. docker --help

command explain
docker --help View all commands
docker command -- help View help information for a command

2. docker info (details)

command explain
docker info Display the system information of docker, including the number of images and containers

3. docker version

command explain
docker version Print docker version information

2. Image command

1. docker images

  • Command: docker images [OPTIONS] [REPOSITORY[:TAG]]

  • Common options:

    Name, shorthand default describe
    --all , -a List all mirrors (hide middle mirror by default)
    --quiet , -q Show only the ID of the image
  • example:

    [root@localhost ~]# docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
    • explain
      • REPOSITORY: the warehouse source of the image (name)
      • TAG: label of the image (version)
      • IMAGE ID: the id of the image
      • CREATED: the creation time of the image
      • SIZE: the SIZE of the mirror

2. docker search (search image in warehouse)

  • Command: docker search [OPTIONS] TERM

  • Common options:

    Name, shorthand default describe
    --filter , -f Filter the output according to the provided conditions in the form of key=value pair.
    Pass multiple flags if there are multiple filters
    (for example -- filter is automated = true -- filter stars = 3)
  • example:

    docker search --filter stars=3 busybox
    NAME                 DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    busybox              Busybox base image.                             325       [OK]

3. docker pull (Download Image)

  • Command: docker pull [OPTIONS] NAME[:TAG|@DIGEST]
    If you do not write tag (version), the default is latest

  • example:

    # Pull the latest version. The following command is equivalent to: docker pull mysql:latest
    docker pull mysql
    # Pull the specified version. Make sure the version exists in the warehouse
    docker pull mysql:5.7

4. docker rmi (delete image)

  • Command: docker rmi [OPTIONS] IMAGE [IMAGE...]
    You can delete one or more images by their name or id

  • Common options:

    Name, shorthand default describe
    --force , -f Force image deletion
  • example:

    # Delete the specified image
    docker rmi -f e73346bdf465
    # Delete all mirrors
    docker rmi -f $(docker images -aq)

5. docker commit (generate image through container)

  • Command: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

  • Common options:

    Name, shorthand default describe
    -m Specify description information to submit
    -a Specify updated user information
  • example:

    # After modifying a tomcat container (app added to the webapps file), 7e119b82cf6 represents a container
    docker commit -a "xiaoMaNong" -m "add webapps app" 7e119b82cff6 tomcat:v01
    # Then check the local image, and you can see the image just submitted
    docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    tomcat              v01                 37af1236adef        15 seconds ago      652 MB

6. docker save/load

  • docker save: save one or more images to tar Archive (streaming to STDOUT by default)

    • Command: docker save [OPTIONS] IMAGE [IMAGE...]

    • Common options:

    Name, shorthand default describe
    --output , -o Write to file instead of STDOUT
  • docker load: load images from tar archive or STDIN

    • Command: docker load [OPTIONS]

    • Common options:

    Name, shorthand default describe
    --input , -i Read from tar archive instead of STDIN
  • example:

    # Save the image to the local tar file
    docker save -o mysql5.7 mysql:5.7
    # There is no extranet on the other server, send the tar package saved above to the server, and then load
    sudo docker load -i mysql5.7

3. Container command

Note: containers can only be created with images

1. docker run (create a new container and start it)

  • Command: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

  • Common options:

    Name, shorthand default describe
    --name="Name" Assign a name to the container. The name is unique. You can use the name to determine the container
    --detach , -d Running in background mode
    -it Run in interactive mode, enter the container to view the content
    --rm Automatically delete container on exit
    --publish , -p Publish the port of the container to the host using:
    -p ip: host port: container port
    -p host port: container port (common)
    -p container port
    Container port
    --publish-all , -P Randomly assign the port of the container to the free port of the host. You can use docker ps -a to view
    --volume, -v Bind the mount directory using the following methods:
    -v / local directory: container directory
    Anonymous mount: - v container directory
    Named mount: - v volume name: container directory
    (see the container data volume for details)
  • example:

Pit for background start-up vessel

When a container is started in the way of later running, the docker ps command is used to find that the container is not running

[root@localhost ~]# docker run --name="centos_test" -d centos
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
  • Reason: if the docker container runs in the background, there must be a foreground process. If the docker finds no application, it will stop automatically.
  • Solution: docker run -dit centos /bin/bash
    • Add it parameter to run interactively
    • Add - d parameter to run in the background
    • In this way, you can start a Centos running in the background all the time
    • Note: to enter the container, use exec instead of attach command. Attach command is to use existing terminal. If you want to exit the container operation, bash will end and the container will exit

2. docker ps (list containers)

  • Command: docker ps [OPTIONS]
    Display as running container by default without any parameters

  • Common options:

    Name, shorthand default describe
    --all , -a Show all containers
    --last , -n=? -1 Display n last created containers (including all States)
    --quiet , -q Show digital ID s only
  • example:

    [root@localhost /]# docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
    6097bc8e3852        centos              "/bin/bash"         10 minutes ago      Exited (0) 9 minutes ago                       sad_lamport
    ea55e44464ae        bf756fb1ae65        "/hello"            3 hours ago         Exited (0) 3 hours ago                         unruffled_chandrasekhar
    • Explanation:
      • IMAGE: IMAGE
      • COMMAND: reference COMMAND
      • CREATED: time when the container was CREATED
      • STATUS: container STATUS
      • PORTS: exposed PORTS
      • NAMES: container name

3. exit/Ctrl + P + Q (exit container)

After docker run -it name enters the container, use the following command to exit the container
exit: container stops and exits
Ctrl + P + Q: container does not stop exiting

4. docker rm (delete container)

  • Command: docker rm [OPTIONS] CONTAINER [CONTAINER...]
    The id/name of the CONTAINER used by the CONTAINER in the command

  • Common options:

    Name, shorthand default describe
    --force , -f Force deletion of running containers (using SIGKILL)
  • example:

    # Delete all containers
    docker rm -f $(docker ps -aq)
    docker ps -aq | xargs docker rm -f

5. docker start/stop

docker start container id/name		# Start container
docker restart container id/name	# Restart container
docker stop container id/name		# Stop the currently running container
docker kill container id/name		# Forced stop container

6.docker exec (enter the currently running container (open a new terminal))

  • Command: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

  • Common options:

    Name, shorthand default describe
    -it Run in interactive mode
  • example:

    docker exec -it centos1 /bin/bash

7. docker attach (enter the currently running container (enter the terminal of the container start command, no new thread will be started))

  • Command: docker attach [OPTIONS] CONTAINER

8. docker cp (copy files / folders between container and local file system)

  • Command:

    # Execute on local system
    # Copy files from the container to the local file system
    # Copy local system files to container

9. docker top (view the process information in the container)

# Similar to the top command in linux
docker top CONTAINER

10. docker logs

  • Command: docker logs [OPTIONS] CONTAINER

  • Common options:

    Name, shorthand default describe
    --follow , -f Trace log output
    --tail all Number of lines to display from the end of the log
    --timestamps , -t presentation time stamp
  • example:

# Show all logs
docker logs -ft centos_test

# Show 10 logs
docker logs -ft --tail 10 centos_test

11. Docker inspection (return container details)

docker inspect CONTAINER

Example (common information marked):

[root@localhost ~]# docker inspect c2b030acf83a
        "Id": "c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6",//Container id, usually the first 12 bits
        "Created": "2020-06-07T15:04:33.788916436Z",//Container creation time
        "Path": "/bin/bash",	//Default console
        "Args": [],	//Parameters passed
        "State": {	//State of container
            "Status": "running",	//Running means running
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 101264,	//Process id
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-06-07T15:04:35.115091831Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        "Image": "sha256:470671670cac686c7cf0081e0b37da2e9f4f768ddc5f6a26102ccd1c6954c1ee",//id of the image
        "ResolvConfPath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/hostname",
        "HostsPath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/hosts",
        "LogPath": "/var/lib/docker/containers/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6/c2b030acf83a23b33471b28d58e20d96f9eb22fceab5ffb9b0a848841a3045b6-json.log",
        "Name": "/zyx",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {	// Host configuration
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
            "ReadonlyPaths": [
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90-init/diff:/var/lib/docker/overlay2/02399b4c6980e3092721d60619f83c651885c0b0eb1241a6417f0bddb44b5463/diff",
                "MergedDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90/merged",
                "UpperDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90/diff",
                "WorkDir": "/var/lib/docker/overlay2/bbe44f663e7c732f43fa3a35633008e8d7027fed9d41400a1aa970d5bdf45c90/work"
            "Name": "overlay2"
        "Mounts": [],	//Data volume mount
        "Config": {		//Basic configuration
            "Hostname": "c2b030acf83a",		//Container name
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [	//Basic environment variables
            "Cmd": [
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "": "20200114",
                "org.label-schema.license": "GPLv2",
                "": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS",
                "org.opencontainers.image.created": "2020-01-14 00:00:00-08:00",
                "org.opencontainers.image.licenses": "GPL-2.0-only",
                "org.opencontainers.image.title": "CentOS Base Image",
                "org.opencontainers.image.vendor": "CentOS"
        "NetworkSettings": {	//Some settings of the network
            "Bridge": "",
            "SandboxID": "70097fb845389da1a20faf75eabb2f84866ba4b38ea8388397a840b9a344aa85",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/70097fb84538",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "cb235799991b3c585bf97ea5fcdfc7a069aa13554a5f84ea35e6172c9cad2ed5",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {		//bridging
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "020a4fab0d00a01941b764d9f16740807b2c2673b8138d7e1ece968086b5475b",
                    "EndpointID": "cb235799991b3c585bf97ea5fcdfc7a069aa13554a5f84ea35e6172c9cad2ed5",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null

4, Container data volume

In Docker, to achieve data persistence (the so-called data persistence of Docker means that data does not end with the end of the container), data needs to be mounted from the host to the container.

1. Type of Mount

(1) volume (most commonly used)

It can be divided into anonymous mount and named mount:

  • Anonymous mount:

    # -v path in container
    docker run -d -P --name nginx01 -v /ect/nginx nginx
  • Named mount:

    # -v volume name: path inside the container
    docker run -d -P --name nginx02 -v nginxConfig:/ect/nginx nginx

You can view the mount information through the docker inspect ion container name or docker volume inspect ion volume name:

"Mounts": [
          "Type": "volume",		//Type of Mount
          "Name": "nginxConfig",//The name of the volume
          "Source": "/var/lib/docker/volumes/nginxConfig/_data",//The local location of the volume (by default, the location of the mounted volume in this way is / var/lib/docker/volumes/_data directory)
          "Destination": "/ect/nginx",//Contents in container
          "Driver": "local",
          "Mode": "z",
          "RW": true,	//Read write support
          "Propagation": ""

(2) bind (more commonly used)

# -v / local directory: container directory
docker run -it -v /home/test:/home centos

When the / home/test directory does not exist locally, Docker will automatically create

You can view the mount information through the docker inspect ion container name:

"Mounts": [
        "Type": "bind",		//Type of Mount
        "Source": "/home/test",	//Local directory
        "Destination": "/home",	//Contents in container
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"

However, bind is not portable in different host systems. For example, the directory structure of Windows and Linux is different, and the host directory that bind points to is not the same. This is also the reason why bind cannot appear in the Dockerfile, because the Dockerfile is not portable.

2. docker volume (volume management command)

# docker volume volume_name / / create a custom container volume
 #docker volume ls / / view all container volumes
 # docker volume inspect volume_name / / view the details of the specified container volume
 # docker volume rm volume_name / / delete custom data volume

3. Authority

  • ro: readonly, which means read-only. It means that this path can only be accessed locally, and cannot be accessed inside the container

    docker run -d -P --name nginx01 -v /ect/nginx:ro nginx
  • rw: readwrite, indicating that it is readable and writable. It is the default.

    docker run -d -P --name nginx01 -v /ect/nginx:rw nginx

4. - volumes from (data volume container)

# Create a new container centos_child, and mount CentOS_ Data volume in the parent container
docker run -it --volumes-from centos_father --name centos_child centos /bin/bash

--The container behind volumes from is the data volume container. Multiple word containers can be created through data volume containers, even if the original data volume container CentOS is deleted_ Father, or delete other containers, but as long as a container is using the data volume, the data in it will not be lost! (unless there are no containers in use)

5, DockerFile

1. Basic knowledge

This part refers to: Docker learning notes (5) - dockerfile

  1. Each reserved key (instruction) must be a capital letter

  2. The Dockerfile file is executed from top to bottom

  3. #Represents a comment

  4. Each instruction creates and commits a new image layer

  5. Docker image is composed of special file systems; the bottom is bootfs, and the bootfs of the host is used. One image can be placed on top of another. The image below is called the parent image, and the bottom image becomes the base image. When starting a container from a mirror, docker loads a read-write file system at the top level as the container. As shown below

2. Basic command

keyword effect remarks
FROM Specify base image Specify that the dockerfile is built on that image, starting here
MAINTAINER Author information It is used to indicate who wrote the dockerfile, generally: Name + email
LABEL label Label can be used to indicate the dockerfile instead of Maintainer. Finally, it can be viewed in the basic information of docker image
RUN Execute command Execute a command in / bin/sh format by default: RUN command or run ["command", "Param1", "param2"]
CMD Container start command Provides the default command when starting the container, which is used with ENTRYPOINT. Format CMD command param1 param2 or CMD ["command", "param1", "param2"]. You can use & & to splice multiple commands in a CMD
ENTRYPOINT entrance Generally, it is used in containers that are closed when executing. The format ENTRYPOINT ["command", "param1", "param2"]
COPY Copy file Copy files to image when build ing
ADD Add file Add files to the image when building, not only limited to the current build context, but also from remote services. If the files are compressed, they will be automatically decompressed
ENV environment variable The environment variable is set when build ing, which can be overridden by - e when starting the container. Format ENV name=value
ARG Build parameters Build parameters are only used when building. If there is ENV, the value of ENV with the same name will always override the arg parameter
VOLUME Define data volumes that can be mounted externally Specifies which directory of build's image can be mounted to the file system when it is started. Use the - v binding format VOLUME ["directory"] when starting the container
EXPOSE Exposed port Define the port to listen to when the container is running, and start the use of - p to bind the exposed port. Format: EXPOSE 8080 or EXPOSE 8080/udp
WORKDIR working directory Specifies the working directory inside the container. If it is not created, it will be created automatically. If the absolute address is specified / used, if it is not / at the beginning, it is the relative path of the path of the previous workdir
USER Specify execution user Specify the user when RUN CMD ENTRYPONT is executed during build or startup
HEALTHCHECK health examination The command to monitor the health monitoring of the current container is basically useless because many times the application has its own health monitoring mechanism
ONBUILD trigger When the image with the ONBUILD keyword is inherited, the command of ONBUILD will be executed after the FROM is executed, but the current image will not be affected
STOPSIGNAL Send semaphore to host The STOPSIGNAL instruction sets the system call signal to be sent to the container to exit.
SHELL Specify the shell to execute the script Specifies the shell used by RUN CMD ENTRYPOINT when executing commands

3. docker build

First, write the Dockerfile file, and then use the docker build command to build the image

  • Command: docker build [OPTIONS] PATH

  • Common options:

    Name, shorthand default describe
    -f Specifies the Dockerfile path to use. If the file is the Dockerfile in the current directory (file name is this), you can specify it without - f
    --tag, -t Image name and label, usually name:tag Or name format; multiple labels can be set for one image in one build.
  • For example, modify the official centos (add vim and net tools), and build your own centos:

    • First write the dockerfile file: 99% of the images in the docker hub start from the scratch (FROM scratch) basic image, and then configure the required software and some configurations to build. Here we start to build directly from centos. The file name is mydockerfile centos:

      FROM centos
      MAINTAINER xiaomanong<zyx1260168395>
      ENV MYPATH /usr/local
      RUN yum -y install vim
      RUN yum -y install net-tools
      EXPOSE 80
      CMD echo $MYPATH
      CMD echo "---end---"
      CMD /bin/bash
    • Using the docker build command to build the image

      # Don't forget that the last dot '.' indicates the current path
      docker build -f mydockerfile-centos -t mycentos:0.1 .
    • Then you can use docker images to view your own image

4. docker history

  • Command: docker history [OPTIONS] IMAGE

  • Common options:

    Name, shorthand default describe
    -H true Print image size and date in a readable format
  • Example: to view the newly created mycentos in 5.3:

# The build process shown is bottom-up
[root@localhost zyx]# docker history mycentos
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
f006331eed43        4 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin...   0B                  
844dae209483        4 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo...   0B                  
9047ac00cd0f        4 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "echo...   0B                  
9052f658149b        4 minutes ago       /bin/sh -c #(nop)  EXPOSE 80                    0B                  
216accbf3204        4 minutes ago       /bin/sh -c yum -y install net-tools             22.8MB              
f036dff75a56        4 minutes ago       /bin/sh -c yum -y install vim                   57.2MB              
86e8dcdb7221        5 minutes ago       /bin/sh -c #(nop) WORKDIR /usr/local            0B                  
58fa1de6f554        5 minutes ago       /bin/sh -c #(nop)  ENV MYPATH=/usr/local        0B                  
613d715c859b        5 minutes ago       /bin/sh -c #(nop)  MAINTAINER xiaomanong<zyx...   0B                  
470671670cac        5 months ago        /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B                  
<missing>           5 months ago        /bin/sh -c #(nop)  LABEL   0B                  
<missing>           5 months ago        /bin/sh -c #(nop) ADD file:aa54047c80ba30064...   237MB               

5. the difference between CMD and ENTRYPOINT

  • CMD: Specifies the command to run when the container is started. Only the last one will take effect and can be replaced
  • ENTRYPOINT: Specifies the command to be run when the container is started. You can append the command

First, there are two images built by dockerfile s:

  • Mirror cmdtest:

    FROM centos
    CMD ["ls","-a"]
  • Image enttest:

    FROM centos
    ENTRYPOINT ["ls","-a"]

Then use the docker run command to create the containers of the two images respectively:

  • Test the image cmdtest:

    # 1. Run without command and execute CMD command in dockerfile
    [root@localhost zyx]# docker run --rm cmdtest
    # 2. After the command is added, the default CMD command in the dockerfile will be replaced
    [root@localhost zyx]# docker run --rm cmdtest ls -al
    total 56
    drwxr-xr-x.   1 root root 4096 Jun 16 14:30 .
    drwxr-xr-x.   1 root root 4096 Jun 16 14:30 ..
    # 3. If you add parameters to the CMD command, an error will be reported
    [root@localhost zyx]# docker run --rm cmdtest -l
    docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"-l\": executable file not found in $PATH": unknown.
  • Test the image enttest:

    # 1. Run without command, the ENTRYPOINT command in the dockerfile will be executed, with the same effect as the CMD
    [root@localhost zyx]# docker run --rm enttest
    # 2. Since ENTRYPOINT is an append command, the actual command executed when starting the container is ls -a ls -al, so an error is reported
    [root@localhost zyx]# docker run --rm enttest ls -al
    ls: cannot access 'ls': No such file or directory
    # 3. Command actually executed when starting the container: ls -a -l
    [root@localhost zyx]# docker run --rm enttest -l
    total 56
    drwxr-xr-x.   1 root root 4096 Jun 16 14:28 .
    drwxr-xr-x.   1 root root 4096 Jun 16 14:28 ..

6. Practice: use your own Tomcat compression package to make Tomcat image

We use our own Tomcat package and JDK8 package to make Tomcat image

  1. First, send the two compressed packets to the server, and then write the Dockerfile file in the same directory:

    FROM centos
    MAINTAINER xiaomanong<zyx1260168395>
    ADD jdk-8u121-linux-x64.tar.gz /usr/local/
    ADD apache-tomcat-9.0.0.M26.tar.gz /usr/local/
    RUN yum -y install vim
    ENV MYPATH /usr/local
    ENV JAVA_HOME /usr/local/jdk1.8.0_121
    ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
    ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.0.M26
    ENV CATALINA_BASH /usr/local/apache-tomcat-9.0.0.M26
    EXPOSE 8080
    CMD /usr/local/apache-tomcat-9.0.0.M26/bin/ && tail -F /usr/local/apache-tomcat-9.0.0.M26/logs/catalina.out
  2. Build image:

    docker build -f  Dockerfile -t mytomcat .
  3. Start a container of the image and use - v to mount the directory:

    docker run -d -p 8080:8080 -v /home/test/mytomcat/webapps:/usr/local/apache-tomcat-9.0.0.M26/webapps -v /home/test/mytomcat/logs:/usr/local/apache-tomcat-9.0.0.M26/logs --name mytomcat mytomcat

7. Publish image to docker hub

(1) Log in to duck hub

Register your account on the ducker hub, and then log in to the docker hub through the command line

  • Command: docker login [OPTIONS] [SERVER]
  • Common options:
    Name, shorthand default describe
    --password , -p password
    --username , -u user name

(2) docker tag image

  • Command: docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
    Note: TARGET_IMAGE format, as shown in the following figure (to use your own docker hub user name, otherwise an error will be reported):

  • Mark the mytomcat image you just made:

    docker tag mytomcat 1260168395/mytomcat:1.0

(3) Publish image to docker hub:

  • Command: docker push [OPTIONS] NAME[:TAG]

  • Send the mytomcat image to the docker hub:

    docker push 1260168395/mytomcat:1.0

(4) Log out docker logout

  • Command: docker logout [SERVER]

8. Publish image to Alibaba cloud container service

  1. Log in to alicloud( ), find the container and image service (for those that cannot be found, please refer to 2.2 to configure Alibaba cloud image acceleration)

  2. Create namespace

  3. Create image warehouse

    1. Click to create image
    2. Fill in warehouse information
    3. Select the code source, which is the local warehouse:
  4. Publish image
    Click the newly created image warehouse to view the details of the image warehouse. How to submit the description and command of the image to the warehouse in the warehouse can be referred to by yourself.

6, Visualization

1. portainer


Just follow the document. Here is a note of my operation

  1. install
    docker volume create portainer_data
    docker run -d -p 9000:9000 --name portainer --restart always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer
  2. The browser can access the 9000 port.

7, Example

1. Deploy Mysql

  1. The server can connect to the Internet and pull the image directly from the warehouse

    docker pull mysql:5.7
  2. If the server cannot connect to the Internet, Download mysql image from a computer with network, save the image locally, send the image to a server without network, and load the image through docker

    1. Save image to local file

      docker save -o mysql5.7 mysql:5.7
    2. Copy the image to a computer without network, and then load the image through docker.

      sudo docker load -i mysql5.7
  3. Start mysql container

    docker run -dit -p 3306:3306 -v /home/mysql/conf:/etc/mysql/conf.d -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123 --name="mysql01" mysql:5.7

2. Deploy Nginx

  1. Search image. You can use the docker search command to search. I recommend the Docker Hub( )Go to search. The first time you enter the Docker Hub, you need to register. After you register and log in, you need to search Nginx directly:

    After clicking in, there will be version information, image use (configuration) and other information.

  2. Pull the image. If there is no network, the processing method is the same as Mysql image

    docker pull nginx
  3. Start an Nginx container

    docker run --name nginx01 -d -p 8080:80 nginx
  4. Then you can use your browser to access Nginx.

    You can use the curl command to access Nginx locally or outside the virtual machine when the firewall is closed

  5. Configuration of Nginx
    Enter the container directly for configuration (generally, there is no vi/vim in the container, and editing is relatively cumbersome, so this method can be understood):

    # Enter container
    [root@localhost ~]# docker exec -it nginx01 /bin/bash
    root@1d97b6e48f57:/# whereis nginx 
    nginx: /usr/sbin/nginx /usr/lib/nginx /etc/nginx /usr/share/nginx
    root@1d97b6e48f57:/# cd /etc/nginx/
    root@1d97b6e48f57:/etc/nginx# ls
    conf.d		koi-utf  mime.types  nginx.conf   uwsgi_params
    fastcgi_params	koi-win  modules     scgi_params  win-utf
    root@1d97b6e48f57:/etc/nginx# vi nginx.conf

3. Deploy Tomcat

  1. Similarly, first search Tomcat on Docker Hub, and then find the corresponding version for pull.

    docker pull tomcat:9.0
  2. Start a Tomcat container

    docker run -d -p 8080:8080 --name tomcat01 tomcat
  3. Some configurations of Tomcat container

    1. In the Tomcat container, the location of Tomcat is / usr/local/tomcat, where the content in the webapps folder is empty and the original content is all in webapps.dist Folder.
    2. The configuration file is located in / usr/local/tomcat/conf/
  4. After there is content in the webapps folder, check whether Tomcat is configured successfully through browser access

Tags: Docker Nginx Tomcat CentOS

Posted on Thu, 25 Jun 2020 01:24:49 -0400 by zipadee