Docker容器管理
Posted Janzen_Q
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Docker容器管理相关的知识,希望对你有一定的参考价值。
一、容器生命周期及启动过程
1、容器生命周期
2、容器启动过程
二、容器管理命令
Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/root/.docker") -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") -D, --debug Enable debug mode -H, --host list Daemon socket(s) to connect to -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") --tls Use TLS; implied by --tlsverify --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") --tlskey string Path to TLS key file (default "/root/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: builder Manage builds config Manage Docker configs container Manage containers context Manage contexts engine Manage the docker engine image Manage images network Manage networks node Manage Swarm nodes plugin Manage plugins secret Manage Docker secrets service Manage services stack Manage Docker stacks swarm Manage Swarm system Manage Docker trust Manage trust on Docker images volume Manage volumes Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container\'s changes cp Copy files/folders between a container and the local filesystem create Create a new container diff Inspect changes to files or directories on a container\'s filesystem events Get real time events from the server exec Run a command in a running container export Export a container\'s filesystem as a tar archive history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on Docker objects kill Kill one or more running containers load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop one or more running containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers version Show the Docker version information wait Block until one or more containers stop, then print their exit codes Run \'docker COMMAND --help\' for more information on a command.
1、启动容器
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地址 --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 #容器启动执行entrypoint命令 -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 #保存交互状态,通常与-d参数联用 --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") #指定容器重启方式 默认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 #分配给容器tty终端,通常联合-i 实现容器交互访问,容器必须支持shell --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 #指定容器工作目录
--restart 四种模式
no 容器退出时不要自动重新启动。默认设置
on-failure[:max-retries] 仅当容器以非零退出状态退出时才重新启动。(可选)限制Docker守护进程尝试重新启动的重试次数
always 无论退出状态如何,始终重新启动容器。当您指定始终时,Docker守护进程将尝试无限期地重新启动容器。容器也将始终在后台进程启动时启动,而与容器的当前状态无关
unless-stopped 无论退出状态如何,都要重新启动容器,包括在守护程序启动时,除非容器在Docker守护程序停止之前处于停止状态。
注意:当容器启动后,如果容器内没有前台运行的进程,容器将自动退出并停止运行
使用 exit 将从容器内退出并停止容器
使用 ctrl+p+q,从容器内退出,不停止容器运行
1.1 使用 hello-world 镜像启动容器
[root@Docker-Ubu1804-p11:~]# docker run hello-world Unable to find image \'hello-world:latest\' locally latest: Pulling from library/hello-world 2db29710123e: Pull complete Digest: sha256:2498fce14358aa50ead0cc6c19990fc6ff866ce72aeb5546e1d59caac3d0d60f Status: Downloaded newer image for hello-world:latest 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. 2. The Docker daemon pulled the "hello-world" 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. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. 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/
1.2、使用一次性命令运行容器
[root@Docker-Ubu1804-p11:~]# docker run alpine echo hello hello [root@Docker-Ubu1804-p11:~]#
1.3、指定运行容器名称
[root@Docker-Ubu1804-p11:~]# docker run --name alpine1 alpine [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1dbebe78a341 alpine "/bin/sh" 5 seconds ago Exited (0) 4 seconds ago alpine1
1.4、运行交互时容器并退出
# 使用 exit 退出 [root@Docker-Ubu1804-p11:~]# docker run -it --name alpine2 alpine sh / # ls bin dev etc home lib media mnt opt proc root run sbin srv sys tmp usr var / # exit [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 9be449b24e1c alpine "sh" 47 seconds ago Exited (0) 28 seconds ago alpine2 1dbebe78a341 alpine "/bin/sh" About a minute ago Exited (0) About a minute ago alpine1
#使用 Ctrl+p+q 退出 [root@Docker-Ubu1804-p11:~]# docker run -it --name alpine3 alpine sh / # ls bin dev etc home lib media mnt opt proc root run sbin srv sys tmp usr var / # [root@Docker-Ubu1804-p11: [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c5d572106164 alpine "sh" 14 seconds ago Up 12 seconds alpine3 9be449b24e1c alpine "sh" About a minute ago Exited (0) About a minute ago alpine2 1dbebe78a341 alpine "/bin/sh" 2 minutes ago Exited (0) 2 minutes ago alpine1 [root@Docker-Ubu1804-p11:~]#
1.5、设置容器内主机名称
[root@Docker-Ubu1804-p11:~]# docker run -it --name alpine3 -h alpine3 alpine / # hostname alpine3 / #
1.6、运行一次性容器,退出后删除(通常用于测试)
[root@Docker-Ubu1804-p11:~]# docker run --rm -it alpine / # hostname 2da5181abd95 / # exit [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 534f8441a227 alpine "/bin/sh" About a minute ago Up About a minute alpine3 9be449b24e1c alpine "sh" About an hour ago Exited (0) About an hour ago alpine2 1dbebe78a341 alpine "/bin/sh" About an hour ago Exited (0) About an hour ago alpine1
[root@Docker-Ubu1804-p11:~]# docker run --rm alpine cat /etc/issue Welcome to Alpine Linux 3.15 Kernel \\r on an \\m (\\l) [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 534f8441a227 alpine "/bin/sh" 3 minutes ago Up 3 minutes alpine3 9be449b24e1c alpine "sh" About an hour ago Exited (0) About an hour ago alpine2 1dbebe78a341 alpine "/bin/sh" About an hour ago Exited (0) About an hour ago alpine1
1.7、启用前台守护式容器
守护式容器
- 能够长期运行
- 无需会话式交互
- 适合运行应用程序或服务
[root@Docker-Ubu1804-p11:~]# docker run nginx /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh /docker-entrypoint.sh: Configuration complete; ready for start up 2023/04/27 16:14:36 [notice] 1#1: using the "epoll" event method 2023/04/27 16:14:36 [notice] 1#1: nginx/1.21.5 2023/04/27 16:14:36 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 2023/04/27 16:14:36 [notice] 1#1: OS: Linux 4.15.0-209-generic 2023/04/27 16:14:36 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576 2023/04/27 16:14:36 [notice] 1#1: start worker processes 2023/04/27 16:14:36 [notice] 1#1: start worker process 30
1.8、启用后台守护式容器
[root@Docker-Ubu1804-p11:~]# docker run --name nginx1 -d nginx ad85b3ce358ad832c491514f2f71fa3f9bf3c79ba7fffb257a61e7780d464d82 [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ad85b3ce358a nginx "/docker-entrypoint.…" 14 seconds ago Up 13 seconds 80/tcp nginx1
1.9、--restart 设置容器开机自启
##通常情况容器在宿主机发生重启后,容器不会自动重新启动
[root@Docker-Ubu1804-p11:~]# docker run --name nginx1 -d nginx 94512d6530943e6ab0934bc740e51ed5ce72cb07743eb1fe33855f8fc798fe93 [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 94512d653094 nginx "/docker-entrypoint.…" 3 seconds ago Up 2 seconds 80/tcp nginx1 [root@Docker-Ubu1804-p11:~]# reboot Channel(Socket) closed from remote host(Docker-Ubuntu-1804-p11) at 00:22:18. Type `help\' to learn how to use Xshell prompt. [C:\\~]$ Last login: Fri Apr 28 00:22:40 2023 from 10.0.0.1 sudo su - janzen@Docker-Ubu1804-p11:~$ sudo su - [sudo] password for janzen: [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 94512d653094 nginx "/docker-entrypoint.…" 59 seconds ago Exited (0) 43 seconds ago nginx1
设置容器自动重启
[root@Docker-Ubu1804-p11:~]# docker run --restart=always --name nginx2 -d nginx 3563284776fd3f2940f3574076f1bc7fc728023a542536d74ff4578302be499e [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3563284776fd nginx "/docker-entrypoint.…" 2 seconds ago Up 1 second 80/tcp nginx2 94512d653094 nginx "/docker-entrypoint.…" 2 minutes ago Exited (0) 2 minutes ago nginx1 [root@Docker-Ubu1804-p11:~]# docker start nginx1 nginx1 [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3563284776fd nginx "/docker-entrypoint.…" 30 seconds ago Up 29 seconds 80/tcp nginx2 94512d653094 nginx "/docker-entrypoint.…" 3 minutes ago Up 2 seconds 80/tcp nginx1 [root@Docker-Ubu1804-p11:~]# reboot Connection closing...Socket close. Connection closed by foreign host. Disconnected from remote host(Docker-Ubuntu-1804-p11) at 00:25:34. Type `help\' to learn how to use Xshell prompt. [C:\\~]$ Last login: Fri Apr 28 00:25:54 2023 from 10.0.0.1 sudo su - janzen@Docker-Ubu1804-p11:~$ sudo su - [sudo] password for janzen: [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3563284776fd nginx "/docker-entrypoint.…" 2 minutes ago Up About a minute 80/tcp nginx2 94512d653094 nginx "/docker-entrypoint.…" 4 minutes ago Exited (0) About a minute ago nginx1
1.10、--privileged 使容器获得root权限
--privileged 可以让容器内的root账号真正拥有root权限,否则 容器内的root只是外部的一个普通用户权限,privileged 启动容器后,可以看到很多宿主机上的设备,并且可以执行mount命令,甚至允许在容器内启动容器
#常规权限启动容器,挂载光盘数据 [root@Docker-Ubu1804-p11:~]# docker run -it --rm centos:7 bash [root@b176345c438e /]# ls anaconda-post.log bin dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var [root@b176345c438e /]# lsblk lsblk: dm-0: failed to get device path lsblk: dm-0: failed to get device path NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sr0 11:0 1 945M 0 rom sda 8:0 0 10G 0 disk |-sda2 8:2 0 1G 0 part |-sda3 8:3 0 9G 0 part `-sda1 8:1 1M 0 part [root@b176345c438e /]# mount /dev/sr0 /mnt mount: permission denied [root@b176345c438e /]# ##privileged 启动容器,挂载光盘数据 [root@Docker-Ubu1804-p11:~]# docker run -it --rm --privileged centos:7 bash [root@4c0deff6df65 /]# ls anaconda-post.log bin dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var [root@4c0deff6df65 /]# lsblk lsblk: dm-0: failed to get device path lsblk: dm-0: failed to get device path NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sr0 11:0 1 945M 0 rom sda 8:0 0 10G 0 disk |-sda2 8:2 0 1G 0 part |-sda3 8:3 0 9G 0 part `-sda1 8:1 1M 0 part [root@4c0deff6df65 /]# mount /dev/sr0 /mnt mount: /dev/sr0 is write-protected, mounting read-only [root@4c0deff6df65 /]# ls /mnt EFI README.diskdefines boot casper dists install isolinux md5sum.txt pics pool preseed ubuntu [root@4c0deff6df65 /]#
2、查看容器信息
2.1、查看当前存在的容器
Usage: docker ps [OPTIONS] List containers Options: -a, --all Show all containers (default shows just running) -f, --filter filter Filter output based on conditions provided --format string Pretty-print containers using a Go template -n, --last int Show n last created containers (includes all states) (default -1) -l, --latest Show the latest created container (includes all states) --no-trunc Don\'t truncate output -q, --quiet Only display numeric IDs -s, --size Display total file sizes
#查看运行中的容器 [root@Docker-Ubu1804-p11:~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d9388e3c2645 janzen/app1 "nginx" 18 seconds ago Up 17 seconds 80/tcp, 443/tcp elegant_lehmann 64757c743e9e nginx "/docker-entrypoint.…" 41 seconds ago Up 40 seconds 80/tcp peaceful_chaplygin #查看存在的所有容器 [root@Docker-Ubu1804-p11:~]# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7507c2d3cb19 janzen/nginx-centos7:1.20.1-v2.0 "nginx" 25 seconds ago Exited (0) 3 seconds ago blissful_booth d9388e3c2645 janzen/app1 "nginx" 2 minutes ago Up 2 minutes 80/tcp, 443/tcp elegant_lehmann 64757c743e9e nginx "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 80/tcp peaceful_chaplygin 1b794f218ced centos:7 "/bin/bash" 3 minutes ago Exited (0) 2 minutes ago compassionate_brattain 0c22ecafcbd4 alpine "/bin/sh" 3 minutes ago Exited (0) 3 minutes ago peaceful_dirac #显示运行中的容器ID [root@Docker-Ubu1804-p11:~]# docker ps -q d9388e3c2645 64757c743e9e #显示所有容器ID [root@Docker-Ubu1804-p11:~]# docker ps -aq 7507c2d3cb19 d9388e3c2645 64757c743e9e 1b794f218ced 0c22ecafcbd4 #显示容器大小 [root@Docker-Ubu1804-p11:~]# docker ps -s -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE 7507c2d3cb19 janzen/nginx-centos7:1.20.1-v2.0 "nginx" 3 minutes ago Exited (0) 2 minutes ago blissful_booth 0B (virtual 562MB) d9388e3c2645 janzen/app1 "nginx" 5 minutes ago Up 5 minutes 80/tcp, 443/tcp elegant_lehmann 2B (virtual 572MB) 64757c743e9e nginx "/docker-entrypoint.…" 5 minutes ago Up 5 minutes 80/tcp peaceful_chaplygin 1.09kB (virtual 141MB) 1b794f218ced centos:7 "/bin/bash" 5 minutes ago Exited (0) 5 minutes ago compassionate_brattain 0B (virtual 204MB) 0c22ecafcbd4 alpine "/bin/sh" 6 minutes ago Exited (0) 6 minutes ago peaceful_dirac 0B (virtual 5.59MB) #显示最新创建的容器 [root@Docker-Ubu1804-p11:~]# docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7507c2d3cb19 janzen/nginx-centos7:1.20.1-v2.0 "nginx" 3 minutes ago Exited (0) 3 minutes ago blissful_booth #查看指定状态容器 [root@Docker-Ubu1804-p11:~]# docker ps -f "status=exited" CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7507c2d3cb19 janzen/nginx-centos7:1.20.1-v2.0 "nginx" 5 minutes ago Exited (0) 4 minutes ago blissful_booth 1b794f218ced centos:7 "/bin/bash" 7 minutes ago Exited (0) 7 minutes ago compassionate_brattain 0c22ecafcbd4 alpine "/bin/sh" 7 minutes ago Exited (0) 7 minutes ago peaceful_dirac
2.2、查看容器内进程
Usage: docker top CONTAINER [ps OPTIONS]
[root@Docker-Ubu1804-p11:~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d9388e3c2645 janzen/app1 "nginx" 9 minutes ago Up 9 minutes 80/tcp, 443/tcp elegant_lehmann 64757c743e9e nginx "/docker-entrypoint.…" 10 minutes ago Up 10 minutes 80/tcp peaceful_chaplygin [root@Docker-Ubu1804-p11:~]# docker top d9388e3c2645 UID PID PPID C STIME TTY TIME CMD root 2994 2969 0 00:45 ? 00:00:00 nginx: master process nginx 999 3029 2994 0 00:45 ? 00:00:00 nginx: worker process
2.3、查看容器资源使用情况
Usage: docker stats [OPTIONS] [CONTAINER...] Display a live stream of container(s) resource usage statistics Options: -a, --all Show all containers (default shows just running) --format string Pretty-print images using a Go template --no-stream Disable streaming stats and only pull the first result --no-trunc Do not truncate output
#查看指定容器资源使用情况 [root@Docker-Ubu1804-p11:~]# docker stats app1 CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 95fef1f3eba4 app1 0.00% 2.391MiB / 959.6MiB 0.25% 976B / 0B 0B / 0B 2 #查看所有容器资源使用情况 [root@Docker-Ubu1804-p11:~]# docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 9542bfcd7012 nginx1 0.00% 2.387MiB / 959.6MiB 0.25% 796B / 0B 0B / 8.19kB 2 95fef1f3eba4 app1 0.00% 2.391MiB / 959.6MiB 0.25% 976B / 0B 0B / 0B 2
2.4、查看容器详细信息
Usage: docker inspect [OPTIONS] NAME|ID [NAME|ID...] Return low-level information on Docker objects Options: -f, --format string Format the output using the given Go template -s, --size Display total file sizes if the type is container --type string Return JSON for specified type
[root@Docker-Ubu1804-p11:~]# docker inspect app1 [ "Id": "95fef1f3eba444ea8df446f4cd2ea09f01bc53874e0633e75f60bf9f24638806", "Created": "2023-04-27T16:58:37.381048713Z", "Path": "nginx", "Args": [], "State": "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 3684, "ExitCode": 0, "Error": "", "StartedAt": "2023-04-27T16:58:37.787117281Z", "FinishedAt": "0001-01-01T00:00:00Z" , "Image": "sha256:4919aacb5ea0aa5d93a5f386f0df115c74cf774ff2df2bd68caf12b66fee3fe7", "ResolvConfPath": "/var/lib/docker/containers/95fef1f3eba444ea8df446f4cd2ea09f01bc53874e0633e75f60bf9f24638806/resolv.conf", "HostnamePath": "/var/lib/docker/containers/95fef1f3eba444ea8df446f4cd2ea09f01bc53874e0633e75f60bf9f24638806/hostname", "HostsPath": "/var/lib/docker/containers/95fef1f3eba444ea8df446f4cd2ea09f01bc53874e0633e75f60bf9f24638806/hosts", "LogPath": "/var/lib/docker/containers/95fef1f3eba444ea8df446f4cd2ea09f01bc53874e0633e75f60bf9f24638806/95fef1f3eba444ea8df446f4cd2ea09f01bc53874e0633e75f60bf9f24638806-json.log", "Name": "/app1", "RestartCount": 0, "Driver": "overlay2", "Platform": "linux", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "docker-default", "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, "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": [ 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/a65f25e477e872b0fd02f56f82ace0898c8f874547cf2d5a88798e74582e2458-init/diff:/var/lib/docker/overlay2/f8d7a1d5eb0d8502ae92b147370ca2f98a04f499ca8d15b9d64e93f77ddf4f60/diff:/var/lib/docker/overlay2/5d97937e774ff42c6d67fbce8ce268f5d8b517e435a077996a7d7e7807ac0a81/diff", "MergedDir": "/var/lib/docker/overlay2/a65f25e477e872b0fd02f56f82ace0898c8f874547cf2d5a88798e74582e2458/merged", "UpperDir": "/var/lib/docker/overlay2/a65f25e477e872b0fd02f56f82ace0898c8f874547cf2d5a88798e74582e2458/diff", "WorkDir": "/var/lib/docker/overlay2/a65f25e477e872b0fd02f56f82ace0898c8f874547cf2d5a88798e74582e2458/work" , "Name": "overlay2" , "Mounts": [], "Config": "Hostname": "95fef1f3eba4", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": "443/tcp": , "80/tcp": , "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": null, "Image": "janzen/nginx-centos7:1.20.1-v2.0", "Volumes": null, "WorkingDir": "", "Entrypoint": [ "nginx" ], "OnBuild": null, "Labels": "author": "janzen<janzen.com>", "description": "Installed nginx-1.20.1-10.el7 by yum", "org.label-schema.build-date": "20201113", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS", "org.opencontainers.image.created": "2020-11-13 00:00:00+00:00", "org.opencontainers.image.licenses": "GPL-2.0-only", "org.opencontainers.image.title": "CentOS Base Image", "org.opencontainers.image.vendor": "CentOS", "version":Docker容器的网络管理和网络隔离
一、Docker网络的管理1、Docker容器的方式
1)Docker访问外网
Docker容器连接到宿主机的Docker0网桥访问外网;默认自动将docker0网桥添加到docker容器中。
2)容器和容器之间通信
需要管理员创建网桥;将不同的容器连接到网桥上实现容器和容器之间相互访问。
3)外部网络访问容器
通过端口映射或者同步docker宿主机网络配置实现通信。
2、Docker容器网络通信的模式
1)bridge
默认容器访问外网通信使用;依赖docker0网桥。
2)none
需要给容器创建独立的网络命名空间;不会给创建的容器配置TCP/IP信息。
3)container
容器和容器通信使用;容器需要共享容器名称空间,通过共享容器名称空间实现不同容器通信。
4)host
容器内部网络和宿主机保持同步。
3、配置bridge网络通信模式
[root@centos01 yum.repos.d]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo <!--安装centos7源--> [root@centos01 ~]# yum -y install docker <!--安装docker--> [root@centos01 ~]# systemctl start docker <!--启动docker--> [root@centos01 ~]# systemctl enable docker <!--设置docker开机自动启动--> [root@centos01 ~]# echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf <!--开启路由功能--> [root@centos01 ~]# sysctl -p <!--刷新配置--> net.ipv4.ip_forward = 1 [root@centos01 ~]# docker pull hub.c.163.com/public/centos:7.2-tools <!--下载镜像--> [root@centos01 ~]# docker images <!--查看镜像--> REPOSITORY TAG IMAGE ID CREATED SIZE hub.c.163.com/public/centos 7.2-tools 4a4618db62b9 3 years ago 515 MB [root@centos01 ~]# docker run -d --net=bridge --name centos7.201 hub.c.163.com/public/centos:7.2-tools <!--配置创建的容器桥接网络通信,容器访问互联网使用--> b308fb5c097fd455073f2f4a280d2660e6943fe1a62d6409e8ebcd3b86469438 [root@centos01 ~]# docker ps <!--查看运行的容器--> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b308fb5c097f hub.c.163.com/public/centos:7.2-tools "/usr/bin/supervisord" 20 seconds ago Up 19 seconds 22/tcp centos7.201 [root@centos01 ~]# ifconfig <!--查看Docker宿主机IP地址信息--> docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 [root@centos01 ~]# docker exec -it centos7.201 /bin/bash <!--登录centos7.201容器--> [root@b308fb5c097f /]# ifconfig <!--查看IP地址--> eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.17.0.2 netmask 255.255.0.0 broadcast 0.0.0.0 [root@b308fb5c097f /]# ping www.baidu.com <!--centos7.201容器ping公网测试--> PING www.a.shifen.com (39.156.66.18) 56(84) bytes of data. 64 bytes from 39.156.66.18: icmp_seq=1 ttl=50 time=18.4 ms 64 bytes from 39.156.66.18: icmp_seq=2 ttl=50 time=18.3 ms 64 bytes from 39.156.66.18: icmp_seq=3 ttl=50 time=16.9 ms [root@b308fb5c097f /]# ping 192.168.100.10 <!--ping宿主机IP测试 --> PING 192.168.100.10 (192.168.100.10) 56(84) bytes of data. 64 bytes from 192.168.100.10: icmp_seq=1 ttl=64 time=0.043 ms 64 bytes from 192.168.100.10: icmp_seq=2 ttl=64 time=0.086 ms 64 bytes from 192.168.100.10: icmp_seq=3 ttl=64 time=0.150 ms
4、配置none网络通信模式
[root@centos01 ~]# docker run -d --net=none --name centos7.202 hub.c.163.com/public/centos:7.2-tools <!--配置docker容器不需要连接到网络,容器无法通信--> e2c4837d67818e7ef4d7cedf964db21d98cabb594d12091d7f69da4e8fb3f30f [root@centos01 ~]# docker ps <!--查看运行的容器--> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e2c4837d6781 hub.c.163.com/public/centos:7.2-tools "/usr/bin/supervisord" 57 seconds ago Up 56 seconds centos7.202 b308fb5c097f hub.c.163.com/public/centos:7.2-tools "/usr/bin/supervisord" 7 minutes ago Up 7 minutes 22/tcp centos7.201 [root@centos01 ~]# docker exec -it centos7.202 /bin/bash <!--登录centos7.202容器--> [root@e2c4837d6781 /]# ifconfig <!--查看IP地址--> lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 [root@e2c4837d6781 /]# ping www.baidu.com <!--ping公网发现是不通的--> ping: unknown host www.baidu.com [root@e2c4837d6781 /]# [root@e2c4837d6781 /]# ping 192.168.100.10 <!--ping宿主机IP地址发现是不通的--> connect: Network is unreachable
5、配置host网络通信模式
[root@centos01 ~]# docker run -d --net=host --name centos7.203 -v /data1 hub.c.163.com/public/centos:7.2-tools <!--配置运行的容器和宿主机网络保持同步--> 2911358be486720c4ee93c8de22cd77301236f48c5baf22ea63bb3c54450032e [root@centos01 ~]# ls /var/lib/docker/volumes/ <!--查看创建的数据卷--> dc755f3b6036f167471435629918d06264e1c2c6a8b175426fa80da36143a87e metadata.db [root@centos01 ~]# docker ps <!--查看运行的容器--> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2911358be486 hub.c.163.com/public/centos:7.2-tools "/usr/bin/supervisord" About a minute ago Up About a minute centos7.203 e2c4837d6781 hub.c.163.com/public/centos:7.2-tools "/usr/bin/supervisord" 15 minutes ago Up 15 minutes centos7.202 b308fb5c097f hub.c.163.com/public/centos:7.2-tools "/usr/bin/supervisord" 21 minutes ago Up 21 minutes 22/tcp centos7.201 [root@centos01 ~]# docker exec -it centos7.203 /bin/bash <!--登录到centos7.203容器--> [root@centos01 /]# ifconfig <!--查看IP地址--> docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.100.10 netmask 255.255.255.0 broadcast 192.168.100.255 ens34: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.0.126 netmask 255.255.255.0 broadcast 192.168.0.255 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 vethc39178a: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet6 fe80::7c4b:a6ff:fe1c:a37f prefixlen 64 scopeid 0x20<link> virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255 [root@centos01 ~]# docker exec -it centos7.203 /bin/bash <!--登录centos7.203容器--> [root@centos01 /]# ping www.baidu.com <!--ping公网测试--> PING www.a.shifen.com (39.156.66.14) 56(84) bytes of data. 64 bytes from 39.156.66.14: icmp_seq=1 ttl=51 time=20.0 ms 64 bytes from 39.156.66.14: icmp_seq=2 ttl=51 time=19.1 ms 64 bytes from 39.156.66.14: icmp_seq=3 ttl=51 time=15.9 ms [root@centos01 /]# ping 192.168.100.10 <!--ping宿主机IP地址测试--> PING 192.168.100.10 (192.168.100.10) 56(84) bytes of data. 64 bytes from 192.168.100.10: icmp_seq=1 ttl=64 time=0.020 ms 64 bytes from 192.168.100.10: icmp_seq=2 ttl=64 time=0.060 ms 64 bytes from 192.168.100.10: icmp_seq=3 ttl=64 time=0.030 ms <!---Centos7.203容器安装Nginx--> [root@centos01 ~]# cp /mnt/nginx-1.6.0.tar.gz ./ <!--拷贝Nginx压缩包--> [root@centos01 ~]# ls anaconda-ks.cfg initial-setup-ks.cfg nginx-1.6.0.tar.gz [root@centos01 ~]# cp nginx-1.6.0.tar.gz /var/lib/docker/volumes/dc755f3b6036f167471435629918d06264e1c2c6a8b175426fa80da36143a87e/_data/ <!--将Nginx压缩包通过数据卷共享到centos7.203容器--> [root@centos01 ~]# docker exec -it centos7.203 /bin/bash <!--登录到centos7.203容器--> [root@centos01 /]# ls anaconda-post.log bin data1 dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var [root@centos01 /]# cd data1/ <!--查看宿主机共享的数据--> [root@centos01 data1]# ls nginx-1.6.0.tar.gz [root@centos01 /]# yum -y install pcre-devel zlib-devel <!--安装Nginx依赖程序--> [root@centos01 /]# useradd -M -s /sbin/nologin nginx <!--创建管理Nginx用户--> [root@centos01 /]# tar zxvf /data1/nginx-1.6.0.tar.gz -C /usr/src/ <!--解压缩Nginx包--> [root@centos01 /]#yum -y install gcc pcre-devel zlib-devel make <!--先安装依赖--> [root@centos01 /]# cd /usr/src/nginx-1.6.0/ [root@centos01 nginx-1.6.0]# ./configure --prefix=/usr/local/nginx --user=nginx --with-http_stub_status_module && make && make install <!--配置Nginx并 编译安装nginx--> [root@centos01 nginx-1.6.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/ <!--优化Nginx执行命令--> [root@centos01 nginx-1.6.0]# echo "www.docker.nginx.com" > /usr/local/nginx/html/index.html <!--修改Nginx网站主页内容--> [root@centos01 nginx-1.6.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/ <!--在centos7.203容器中启动Nginx服务--> [root@centos01 nginx-1.6.0]# netstat -anptu | grep nginx <!--监听Nginx服务端口号是否正在运行--> tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 6268/nginx: master [root@centos01 ~]# curl http://192.168.100.10 <!--docker宿主机访问centos7.203容器中的nginx--> www.docker.nginx.com [root@centos01 nginx-1.6.0]# cat /usr/local/nginx/logs/access.log <!--查看centos7.203容器中成功访问Nginx的日志--> 192.168.100.10 - - [12/May/2020:21:42:47 +0800] "GET / HTTP/1.1" 200 21 "-" "curl/7.29.0"
6、配置docker0网卡参数
[root@centos01 ~]# ifconfig <!--查看docker宿主机IP地址--> docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 [root@centos01 ~]# systemctl stop docker <!--停止docker服务--> [root@centos01 ~]# ip link set dev docker0 down <!--停止docker0网桥--> [root@centos01 ~]# brctl delbr docker0 <!--删除系统默认的docker0网桥--> [root@centos01 ~]# brctl addbr docker0 <!--创建新的网桥,名字是docker0--> [root@centos01 ~]# ip addr add 192.168.20.1/24 dev dokcer0 <!--新的网桥docker0配置IP地址--> [root@centos01 ~]# ip link set dev docker0 up <!--启动新的docker0网桥--> [root@centos01 ~]# vim /etc/docker/daemon.json <!--修改docker配置文件加载新的网桥docker0--> {"registry-mirrors":["https://6kx4zyno.mirror.aliyuncs.com"]} {"bip":"192.168.20.1/24"} <!--加此行--> [root@centos01 ~]# systemctl start docker <!--启动docker服务--> [root@centos01 ~]# ifconfig <!--查看docker宿主机IP详细信息--> docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.20.1 netmask 255.255.255.0 broadcast 0.0.0.0 [root@centos01 ~]# docker run -it -d --name centos7.2v1 hub.c.163.com/public/centos:7.2-tools <!--创建一个容器在后台运行--> d0b5392e60cef37f3c44d79a9fb73916720cfc44faa7b73862bee05fb2d6ce7b [root@centos01 ~]# docker exec -it centos7.2v1 /bin/bash <!--登录centos7.2v1容器--> [root@d0b5392e60ce /]# ifconfig <!--查看IP地址详细信息--> eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.20.2 netmask 255.255.255.0 broadcast 0.0.0.0
二、Docker网络隔离
1、Docker网络隔离原理
需要管理创建网络空间名称;将不同的容器加载到不同的网络空间名称中实现隔离;默认不配置网络隔离默认给容器分配的docker0网络空间名称。
2、Docker容器自带的网络空间名称类型
bridge:容器桥接到docker0网桥上;
host:容器同步docker宿主机的网络配置信息;
none:不创建网络,docker容器不需要配置TCP/IP信息;
3、配置Docker网络名称空间隔离
[root@centos01 ~]# docker network ls <!--查看docker默认的网络名称空间--> NETWORK ID NAME DRIVER SCOPE 8bb953004416 bridge bridge local 2c18234cad82 host host local 67860e823c36 none null local [root@centos01 ~]# docker network create -d bridge liyanxin <!--创建网络名称空间--> 0c69de4672ec173dc4c60b19e0bf93b361f45a804859f7bc2105d85ca83b1169 [root@centos01 ~]# docker network create -d bridge gongsunli <!--创建网络名称空间--> 35687468c9034262173a96e9c23e045cbb8b7ffa6648fc84e015504740815001 [root@centos01 ~]# ifconfig <!--查看docker宿主机网卡信息--> br-0c69de4672ec: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 172.18.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 br-35687468c903: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 172.19.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 [root@centos01 ~]# docker run -it -d --name centos6.701 --network=liyanxin hub.c.163.com/public/centos:6.7-tools <!--创建运行的容器添加到liyanxin网络名称空间中隔离--> b85a2d8419a98756369ddc3b78247d3d42c178e8e563a936fe973f2f6611f951 [root@centos01 ~]# docker exec -it centos6.701 /bin/bash <!--登录centos6.701容器--> [root@b85a2d8419a9 /]# ifconfig <!--查看IP地址--> eth0 Link encap:Ethernet HWaddr 02:42:AC:12:00:02 inet addr:172.18.0.2 Bcast:0.0.0.0 Mask:255.255.0.0 [root@centos01 ~]# docker run -it -d --name centos6.702 --network=gongsunli hub.c.163.com/public/centos:6.7-tools <!--创建运行的容器添加到gongsunli网络名称空间中隔离--> 9af0fb7b85af3270f3c7c44b62438f436b22289ac0a7604d6ed522604b7b185f [root@centos01 ~]# docker exec -it centos6.702 /bin/bash <!--登录centos6.702容器--> [root@9af0fb7b85af /]# ifconfig <!--查看IP地址--> eth0 Link encap:Ethernet HWaddr 02:42:AC:13:00:02 inet addr:172.19.0.2 Bcast:0.0.0.0 Mask:255.255.0.0
三、配置网桥实现网络隔离
1、配置网桥实现网络隔离的目的
实现Docker宿主机的容器跨Docker宿主机的容器通信使用。
2、配置网桥实现网络隔离原理
将物理网卡桥接到创建的网桥网卡上;给网桥网卡配置IP地址;创建容器加载网桥网卡实现;docker宿主机容器跨docker宿主机容器通信;管理员管理docker宿主机通过网桥网卡进行远程管理
3、配置docker网桥实现网络隔离
[root@centos01 ~]# vim /etc/sysconfig/network-scripts/ifcfg-ens32 <!--修改docker宿主机物理网卡桥接到网桥网卡br0--> TYPE=Ethernet PROXY_METHOD=none BROWSER_ONLY=no BOOTPROTO=static DEFROUTE=yes NAME=ens32 DEVICE=ens32 ONBOOT=yes BRIDGE=br0 <!--添加此行--> [root@centos01 ~]# cp /etc/sysconfig/network-scripts/ifcfg-ens32 /etc/sysconfig/network-scripts/ifcfg-br0 <!--创建并生成br0网桥--> [root@centos01 ~]# vim /etc/sysconfig/network-scripts/ifcfg-br0 <!--编辑br0网卡配置文件--> TYPE=Bridge <!--修改此行--> PROXY_METHOD=none BROWSER_ONLY=no BOOTPROTO=static DEFROUTE=yes NAME=br0 <!--修改名字--> DEVICE=br0 <!--修改名字--> ONBOOT=yes IPADDR=192.168.100.10 <!--添加宿主机IP地址--> NETMASK=255.255.255.0 [root@centos01 ~]# systemctl restart network <!--重新启动docker宿主机网卡服务--> [root@centos01 ~]# ifconfig <!--查看docker宿主机网卡信息--> br0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.100.10 netmask 255.255.255.0 broadcast 192.168.100.255 br-0c69de4672ec: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.18.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 br-35687468c903: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.19.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 ether 00:0c:29:18:d3:26 txqueuelen 1000 (Ethernet) ens34: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet6 fe80::4ad2:dd37:4341:5d8e prefixlen 64 scopeid 0x20<link> lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 veth7b0bb5f: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet6 fe80::ccd3:86ff:fee6:5725 prefixlen 64 scopeid 0x20<link> veth7e0f471: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet6 fe80::684c:fdff:fe13:b436 prefixlen 64 scopeid 0x20<link> virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255 [root@centos01 ~]# yum -y install git <!--docker宿主机安装git--> [root@centos01 ~]# git clone https://github.com/jpetazzo/pipework <!--下载docker容器网络管理工具pipework--> [root@centos01 ~]# cp pipework/pipework /usr/local/bin/ <!--优化管理命令--> [root@centos01 ~]# chmod +x /usr/local/bin/pipework <!--添加执行权限--> [root@centos01 ~]# docker run -d --name centos6.703 --network=none hub.c.163.com/public/centos:6.7-tools <!--通过镜像运行容器--> adea0ad48bdde947ec595382d96cba06eb6522ec046e9b3c7bfcb1edb5c84545 [root@centos01 ~]# pipework br0 centos6.703 192.168.100.101/24 <!--给centos6.703容器配置IP地址--> [root@centos01 ~]# docker exec -it centos6.703 /bin/bash <!--登录centos6.703容器--> [root@adea0ad48bdd /]# ifconfig <!--查看IP地址--> eth1 Link encap:Ethernet HWaddr FA:3A:9D:ED:C0:FF inet addr:192.168.100.101 Bcast:192.168.100.255 Mask:255.255.255.0 [root@adea0ad48bdd /]# ping 192.168.100.10 PING 192.168.100.10 (192.168.100.10) 56(84) bytes of data. 64 bytes from 192.168.100.10: icmp_seq=1 ttl=64 time=0.100 ms 64 bytes from 192.168.100.10: icmp_seq=2 ttl=64 time=0.097 ms 64 bytes from 192.168.100.10: icmp_seq=3 ttl=64 time=0.039 ms
4、配置docker宿主机容器和docker宿主机容器通信
[root@centos02 ~]# ping www.baidu.com <!--再新开一台服务器,连接公网,安装docker--> PING www.a.shifen.com (39.156.66.18) 56(84) bytes of data. 64 bytes from 39.156.66.18 (39.156.66.18): icmp_seq=1 ttl=51 time=19.5 ms 64 bytes from 39.156.66.18 (39.156.66.18): icmp_seq=2 ttl=51 time=17.3 ms 64 bytes from 39.156.66.18 (39.156.66.18): icmp_seq=3 ttl=51 time=18.1 ms [root@centos02 ~]# cd /etc/yum.repos.d/ [root@centos02 yum.repos.d]# ls local.repo [root@centos02 yum.repos.d]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo <!--下载centos7源--> [root@centos02 ~]# yum install docker -y <!--安装docker--> [root@centos02 ~]# systemctl start docker <!--启动docker--> [root@centos02 ~]# systemctl enable docker <!--设置开机自动启动--> [root@centos02 ~]# docker pull hub.c.163.com/public/centos:6.7-tools <!--下载镜像--> [root@centos02 ~]# docker images <!--查看镜像--> REPOSITORY TAG IMAGE ID CREATED SIZE hub.c.163.com/public/centos 6.7-tools b2ab0ed558bb 3 years ago 602 MB [root@centos02 ~]# vim /etc/sysconfig/network-scripts/ifcfg-ens32 <!--修改docker宿主机网卡配置信息桥接到br0网卡 --> TYPE=Ethernet PROXY_METHOD=none BROWSER_ONLY=no BOOTPROTO=static DEFROUTE=yes NAME=ens32 DEVICE=ens32 ONBOOT=yes BRIDGE=br0 <!--添加此行--> [root@centos02 ~]# cp /etc/sysconfig/network-scripts/ifcfg-ens32 /etc/sysconfig/network-scripts/ifcfg-br0 <!--创建并生成br0网桥--> [root@centos02 ~]# vim /etc/sysconfig/network-scripts/ifcfg-br0 <!--编辑br0网卡配置文件--> TYPE=Bridge <!--修改为Bridge--> PROXY_METHOD=none BROWSER_ONLY=no BOOTPROTO=static DEFROUTE=yes NAME=br0 <!--修改名字--> DEVICE=br0 <!--修改为br0--> ONBOOT=yes IPADDR=192.168.100.20 <!--添加宿主机IP地址--> NETMASK=255.255.255.0 [root@centos02 ~]# systemctl restart network <!--重新启动docker宿主机网卡服务--> [root@centos02 ~]# ifconfig <!--查看docker宿主机网卡信息--> br0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.100.20 netmask 255.255.255.0 broadcast 192.168.100.255 docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 172.17.0.1 netmask 255.255.0.0 broadcast 0.0.0.0 ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 ether 00:0c:29:97:5c:9f txqueuelen 1000 (Ethernet) ens34: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.0.104 netmask 255.255.255.0 broadcast 192.168.0.255 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255 [root@centos02 ~]# yum -y install git <!--安装git--> [root@centos02 ~]# git clone https://github.com/jpetazzo/pipework <!--下载docker容器网络管理工具pipework--> [root@centos02 ~]# cp pipework/pipework /usr/local/bin/ <!--优化管理命令--> [root@centos02 ~]# chmod +x /usr/local/bin/pipework <!--添加执行权限--> [root@centos02 ~]# docker run -d --name centos6.7 --network=none hub.c.163.com/public/centos:6.7-tools <!--通过进行运行容器--> abec0a6bd3822a2fd702dc44d1cf3043648aadd1a661e577c23701e30ee9df7a [root@centos02 ~]# pipework br0 centos6.7 192.168.100.102/24 <!--给centos6.7容器配置IP地址--> [root@centos02 ~]# docker exec -it centos6.7 /bin/bash <!--登录centos6.7容器--> [root@abec0a6bd382 /]# ifconfig <!--查看IP地址--> eth1 Link encap:Ethernet HWaddr EE:01:B7:99:90:1C inet addr:192.168.100.102 Bcast:192.168.100.255 Mask:255.255.255.0 [root@abec0a6bd382 /]# ping 192.168.100.101 <!----> PING 192.168.100.101 (192.168.100.101) 56(84) bytes of data. 64 bytes from 192.168.100.101: icmp_seq=1 ttl=64 time=0.660 ms 64 bytes from 192.168.100.101: icmp_seq=2 ttl=64 time=0.865 ms 64 bytes from 192.168.100.101: icmp_seq=3 ttl=64 time=0.382 ms [root@abec0a6bd382 /]# ping 192.168.100.10 <!----> PING 192.168.100.10 (192.168.100.10) 56(84) bytes of data. 64 bytes from 192.168.100.10: icmp_seq=1 ttl=64 time=0.632 ms 64 bytes from 192.168.100.10: icmp_seq=2 ttl=64 time=0.732 ms 64 bytes from 192.168.100.10: icmp_seq=3 ttl=64 time=0.796 ms [root@abec0a6bd382 /]# ping 192.168.100.20 <!----> PING 192.168.100.20 (192.168.100.20) 56(84) bytes of data. 64 bytes from 192.168.100.20: icmp_seq=1 ttl=64 time=0.144 ms 64 bytes from 192.168.100.20: icmp_seq=2 ttl=64 time=0.094 ms 64 bytes from 192.168.100.20: icmp_seq=3 ttl=64 time=0.043 ms
———————— 本文至此结束,感谢阅读 ————————
以上是关于Docker容器管理的主要内容,如果未能解决你的问题,请参考以下文章