Docker entry to actual combat (2)

Use of Docker images

The official docker image library is relatively slow. Before performing the image operation, you need to set the image source to a domestic site. Create a new file /etc/docker/daemon.json and enter the following content:

{
    "registry-mirrors" : [
        "https://registry.docker-cn.com",
        "https://docker.mirrors.ustc.edu.cn",
        "http://hub-mirror.c.163.com",
        "https://cr.console.aliyun.com/"
    ]
}

Then restart the docker service:

systemctl restart docker

3.1 List all local mirrors

Execute the command docker images to view

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              20.04               f643c72bc252        5 weeks ago         72.9MB
hello-world         latest              bf756fb1ae65        12 months ago       13.3kB

Currently, I only have the two mirrors I just installed locally.

3.2 Find mirrors from the mirror library

Execute the command docker search image name to search for images from the docker image library.

$ docker search python
NAME                             DESCRIPTION                                     STARS              OFFICIAL          AUTOMATED
python                           Python is an interpreted, interactive, objec…   5757                [OK]                
django                           Django is a free web application framework, …   1039                [OK]                
pypy                             PyPy is a fast, compliant alternative implem…   260                 [OK]                
joyzoursky/python-chromedriver   Python with Chromedriver, for running automa…   57                                      [OK]
nikolaik/python-nodejs           Python with Node.js                             57                                      [OK]
arm32v7/python                   Python is an interpreted, interactive, objec…   53                                      
circleci/python                  Python is an interpreted, interactive, objec…   42                                      
centos/python-35-centos7         Platform for building and running Python 3.5…   38                                      
centos/python-36-centos7         Platform for building and running Python 3.6…   30                                      
hylang                           Hy is a Lisp dialect that translates express…   29                  [OK]                
arm64v8/python                   Python is an interpreted, interactive, objec…   24                                      
revolutionsystems/python         Optimized Python Images                         18                                      
centos/python-27-centos7         Platform for building and running Python 2.7…   17                                      
bitnami/python                   Bitnami Python Docker Image                     10                                      [OK]
publicisworldwide/python-conda   Basic Python environments with Conda.           6                                       [OK]
d3fk/python_in_bottle            Simple python:alpine completed by Bottle+Req…   5                                       [OK]
dockershelf/python               Repository for docker images of Python. Test…   5                                       [OK]
clearlinux/python                Python programming interpreted language with…   4                                       
i386/python                      Python is an interpreted, interactive, objec…   3                                       
ppc64le/python                   Python is an interpreted, interactive, objec…   2                                       
centos/python-34-centos7         Platform for building and running Python 3.4…   2                                       
amd64/python                     Python is an interpreted, interactive, objec…   1                                       
ccitest/python                   CircleCI test images for Python                 0                                       [OK]
s390x/python                     Python is an interpreted, interactive, objec…   0                                       
saagie/python                    Repo for python jobs                            0

It is best to choose an official (OFFICIAL) mirror, which is the most stable.

3.3 Download a new image

Execute the command docker pull image name: version number to download the new image.

$ docker pull python:3.8
3.8: Pulling from library/python
6c33745f49b4: Pull complete 
ef072fc32a84: Pull complete 
c0afb8e68e0b: Pull complete 
d599c07d28e6: Pull complete 
f2ecc74db11a: Pull complete 
26856d31ce86: Pull complete 
2cd68d824f12: Pull complete 
7ea1535f18c3: Pull complete 
2bef93d9a76e: Pull complete 
Digest: sha256:9079aa8582543494225d2b3a28fce526d9a6b06eb06ce2bac3eeee592fcfc49e
Status: Downloaded newer image for python:3.8
docker.io/library/python:3.8

After the image is downloaded, you can use the image to create a container.

Use of Docker containers

4.1 Start the container

Execute the command docker run to start the container, that is, to create an instance of a certain image. The docker run command is very complicated, you can first execute a docker run --help to view the help:

$ docker run --help

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

For example, if we want to execute the python shell, we need to add the -it parameter, namely: docker run -it python:3.8

$ docker run -it python:3.8 
Python 3.8.7 (default, Dec 22 2020, 18:46:25) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

4.2 Mount the host's files to the container

The docker container is isolated from the host. To allow programs in the container to access files on the host, you need to mount the host's files into the container through the -v parameter. For example, we have a hello.py on the host machine, which can print hello. If we want to execute it in the python container, we need to mount it. After -v, two parameters are needed, which are the directory of the host and the directory in the container. The two are separated by :, and the path must be an absolute path. My hello.py is saved in the /docker_test directory of the main directory, mount this directory to the /docker_test directory of the container, and then execute python /docker_test/hello.py in the container:

$ docker run -v ~/docker_test:/docker_test python:3.8 python /docker_test/hello.py
hello

4.3 Port mapping for containers

Let's modify hello.py, create a socket server, and listen to port 5000. When a client connects, print the client's address. First, the client sends hello, and then closes the connection:

import socket

ip_port = ('127.0.0.1', 5000)

sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)

while True:
    print('server waiting...')
    conn,addr = sk.accept()
    print(addr)
    conn.sendall(b'hello\n')
    conn.close()

Execute inside the container:

docker run -v ~/docker_test:/docker_test python:3.8 python /docker_test/hello.py

Next, try to connect with the telnet command, but it fails. The reason is that 127.0.0.1 is the ip address of the host, and 5000 is the port of the container, which is slightly different from our habits. In fact, the docker container is very lightweight and does not have its own network. To access the port of the container, port mapping is required to map a certain port of the container to the port of the host. When the client connects, it only needs to connect with Just connect to the port of the host machine.

It should be noted that the server created by the above code cannot be connected by the client anyway, because the ip of 127.0.0.1 is bound in the code. When running in the container, all ips need to be bound, that is, 0.0.0.0 .

import socket

ip_port = ('0.0.0.0', 5000)

sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)

while True:
    print('server waiting...')
    conn,addr = sk.accept()
    print(addr)
    conn.sendall(b'hello\n')
    conn.close()

Then, use the -p parameter. -p also needs three parameters, namely the host's ip address, the host's port, and the container's port. Use: to separate the three. Generally, you can omit the IP address of the host, and only write the port of the host: the port of the container.

docker run -v ~/docker_test:/docker_test -it -p 5001:5000 python:3.8 python /docker_test/hello.py

In this way, port 5000 of the container is mapped to port 5001 of the host, using:

telnet 127.0.0.1 5001

You can connect to the server in the container.

4.4 Container Management

After the above service is running, you can use the docker ps command to view the running containers:

$ docker ps
CONTAINER ID     IMAGE           COMMAND                  CREATED           STATUS         PORTS                    NAMES
ec4c86b8a163     python:3.8      "python /docker_test…"   5 seconds ago     Up 4 seconds   0.0.0.0:5000->5000/tcp   eager_wilson

The displayed content has the following columns:

  • CONTAINER ID: Container ID
  • IMAGE: image name and version
  • COMMAND: the command to execute
  • CREATED: container creation time
  • STATUS: the status of the container
  • PORTS: port mapping
  • NAMES: container name

To kill a container, use the docker kill container ID command.

Guess you like

Origin blog.csdn.net/qq_28165595/article/details/131877951