Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Basic commands for containers

1. Run the container

## docker run -p 8080:80 -d daoCloud. IO /nginx docker run --name: indicates the name of the container. -d: indicates that the next process is running. -p 8080:80 maps the nginx port number 80 on the VM to the local 8080. Run the container in interactive mode, usually in conjunction with -t. -T: reassigns a pseudo-input terminal to the container, usually in conjunction with -i. It: Runs in interactive mode to enter the container to view its contentsCopy the code

Start and run the container

docker run -it centos /bin/bash
Copy the code

2. Query the running container

### docker ps -a: lists all containers that have been run in history + currently running containers -l: displays the most recently created containers -n: displays the last N created containers -q: silent mode, displays only the container number --no-trunc: does not truncate the outputCopy the code

3. Copy files between the local host and the container

For example, copy index.html to replace the default index.html page of nginx

docker cp ./index.html 1a2aa74fb4e5://usr/share/nginx/html

4. Start the container

Start the stopped container

docker start
Copy the code

Restart the container

docker restart
Copy the code

Background startup container

docker run -d centos
Copy the code

There’s a pit here

[root@iZ2ze8f268fd4hso5clji8Z ~]# docker run -d centos 8671b9255fcb2f72751a0bf0d24c9d52195c7b6aae9bab05b4e392b830bfc5e5 [root@iZ2ze8f268fd4hso5clji8Z ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES [root@iZ2ze8f268fd4hso5clji8Z ~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8671b9255fcb centos “/bin/bash” 7 seconds ago Exited (0) 6 seconds ago stupefied_zhukovsky

Docker was started through -d, but docker ps found that it was not started. What is the reason?

This is because Docker decided that the container was not being used, so it stopped.

Note: To start a background process, docker must have a foreground process call it. Otherwise, Docker will automatically stop it if it finds it is not being used.

Such is the case with nginx servers. When the container starts and finds it has no service, it stops immediately.

5. Stop the Docker container

Docker stop Container IDCopy the code

6. Query container logs

Docker logs -f Trace log output -t Print time stamp -n or --tail Number of log lines to printCopy the code

Query logs:

Docker logs -ft --tail 10 Container name Example: Start the centos in the background and keep printing logs. [root@iZ2ze8f268fd4hso5clji8Z ~]# docker run -d centos /bin/bash -c "while true; do echo test; sleep 1; done" 730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2 [root@iZ2ze8f268fd4hso5clji8Z ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 730EE45DF27d centos "/bin/bash -c 'while..." 4 seconds ago Up 3 seconds crazy_heisenberg [root@iZ2ze8f268fd4hso5clji8Z ~]# docker logs -ft -n 10 730ee45df27d 2021-09-27T11:43:45.214069586Z test 2021-09-27T11:43:46.215681065Z test 2021-09-27T11:43:47.217170501Z test 2021-09-27T11:43:47.217170501Z test Test: the 2021-09-27 T11 43:48. 218729587 zCopy the code

7. View the processes in the container

Command: Docker top Container ID [root@iZ2ze8f268fd4hso5clji8Z ~]# docker top 730EE45DF27D UID PID PPID C STIME TTY root 40908 40888 0 Parts? root 41183 40908 0 19:47 ?Copy the code

8. View the metadata of the mirror

命令: docker inspect 容器id
​
​
测试
[root@iZ2ze8f268fd4hso5clji8Z ~]# docker inspect 730ee45df27d
[
    {
        "Id": "730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2",
        "Created": "2021-09-27T11:43:36.761377838Z",
        "Path": "/bin/bash",
        "Args": [
            "-c",
            "while true; do echo test; sleep 1; done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 40908,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-09-27T11:43:37.203100727Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2/hostname",
        "HostsPath": "/var/lib/docker/containers/730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2/hosts",
        "LogPath": "/var/lib/docker/containers/730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2/730ee45df27df144eb7533d1f5b0676c79fac68546e84dfff7ba9b2a16f933e2-json.log",
        "Name": "/crazy_heisenberg",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "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,
            "CgroupnsMode": "host",
            "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": [
                0,
                0
            ],
            "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": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/6f2a5b4f663926bceeef1e22e3181367ca9c7e30980f27a49d81a2f5f7d10032-init/diff:/var/lib/docker/overlay2/5bd0304415d4744ae90a7472c8b54e5b21b91b2a2487350f9783cca03fde0422/diff",
                "MergedDir": "/var/lib/docker/overlay2/6f2a5b4f663926bceeef1e22e3181367ca9c7e30980f27a49d81a2f5f7d10032/merged",
                "UpperDir": "/var/lib/docker/overlay2/6f2a5b4f663926bceeef1e22e3181367ca9c7e30980f27a49d81a2f5f7d10032/diff",
                "WorkDir": "/var/lib/docker/overlay2/6f2a5b4f663926bceeef1e22e3181367ca9c7e30980f27a49d81a2f5f7d10032/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "730ee45df27d",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash",
                "-c",
                "while true; do echo test; sleep 1; done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20210915",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "ab23a522803ad96e35a57d9a012e8339c271eec859041800e285e46248d09731",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/ab23a522803a",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "17e1e833c474ead88be155d7f14736d1e6330b95ece4eed0d6988272b170c204",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "e77f06f74488d7f8cc7b38311a435c88d18508a786d650ca49a1774df7a2bf28",
                    "EndpointID": "17e1e833c474ead88be155d7f14736d1e6330b95ece4eed0d6988272b170c204",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]
Copy the code

There’s a lot of information in there

9. Save the changes as the new image

docker commit -m ‘fun’ 2a2f3a5c960f fun-nginx

This code commits the changes made to the Docker container and calls it fun. The container name is fun-nginx.

After executing this code, a new image is generated.

Let’s see how many nginx mirrors there are now

There are now two mirrors, of which Fun-Nginx is the one we just built. We can delete one.

10. Exit the container

CTRL +P+Q: The container does not stop exitingCopy the code

11. Delete the container

Delete containers that are not running

Docker RM Container ID1 Container ID2....Copy the code

Delete a running container

Docker rm -f Specifies the container nameCopy the code

Delete all containers

docker rm -f $(docker ps -aq)
Copy the code

Four important.

1. Start the daemon container

The docker run -d container name is started in the background processCopy the code

When you start a container using a daemon, there is a problem: using docker ps -a, you find that the container has exited

Important: When docker container is running in the background, it must have a foreground process, and the commands run by the container will exit automatically if they are not those commands that have been suspended (such as top, tail). This is the mechanism of Docker, such as web container. Take Nginx as an example. Under normal circumstances, we only need to start the corresponding service to configure and start the service, such as: service nginx start. However, by doing so, Nginx runs in background mode, resulting in no running applications in the Docker foreground. Such a container after the background start, will immediately commit suicide, because he felt no yo 碃 can do. Therefore, the best solution is to run your application as a console process

docker run -d nginx /bin/sh -c "while true; do echo hello zzyy; sleep 2; done"
Copy the code

Continue to print Hello zzyy on the console every 2 seconds

2. View container logs

Docker logs -f -t --tail Digital container ID -t: indicates that the timestamp is added. -f: indicates that the latest logs are printed. --tail number: indicates the maximum number of logsCopy the code

3. View the processes running in the container

Docker Top Container IDCopy the code

4. Look inside the container for details

Docker inspect Container IDCopy the code

Inspect looks inside the Docker container, which is made up of onion rings, layer upon layer

5. Enter the running container and interact with it on the command line

Docker attach container ID docker attach container IDCopy the code

Example: Now run a container

docker run -d 
Copy the code

If you want to exit the container, CTR + C

When you want to access the container, you enter the root directory of the container

Docker Attach Container IDCopy the code

Use exec to execute the query content in the container and return the result of the execution

Docker exec -t Container ID ls -l/TMP /Copy the code

6. Copy files from the container to the host

Docker cp Container ID: indicates the IP address of the target host in the container pathCopy the code

Search data: www.bilibili.com/video/BV1og…