docker

docker部署

[root@docker-nodde1 docker]# cat /etc/yum.repos.d/docker.repo

[docker]

name=docker-ce

baseurl=https://mirrors.aliyun.com/docker-ce/linux/rhel/9/x86_64/stable/

gpgcheck=0

安装docker

[root@docker-nodde1 docker]# yum install docker-ce -y

[root@docker-nodde1 ~]# vim /usr/lib/systemd/system/docker.service

ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

设定其使用iptables的网络设定方式,默认使用nftables

[root@docker-nodde1 ~]# docker info

二docker的基本操作

[root@docker-nodde1 ~]# docker search nginx

注意可以参考阿里云设置一个镜像加速器

从镜像仓库中拉取镜像

[root@docker-nodde1 ~]# docker pull busybox

[root@docker-nodde1 ~]# docker pull nginx:1.26-alpine

[root@docker-nodde1 ~]# docker images #查看本地镜像

[root@docker-nodde1 ~]# docker image inspect nginx:1.26-alpine #查看镜像信息

#保存镜像

[root@docker-nodde1 ~]# docker image save nginx:latest -o nginx-latest.tar.gz

[root@docker-nodde1 ~]# docker image save nginx:latest nginx:1.26-alpine -o nginx.tag.gz

###保存所有镜像

[root@docker-nodde1 ~]# docker save `docker images | awk 'NR>1{print $1":"$2}'` -o images.tar.gz

-o:指定导出镜像的位置;

指定.tar.gz 可以导出并压缩。
删除镜像

[root@docker-nodde1 ~]# docker rmi nginx:latest

[root@docker-nodde1 ~]# docker rmi `docker images | awk 'NR>1{print $1":"$2}'`
启动容器

[root@docker-nodde1 ~]# docker run -d --name mario -p 80:8080 timinglee/mario

faac8adbd3237c89c7c2d7acc92ea4bb0381bfc26e5274c4ac900ff4fca213fd

[root@docker-nodde1 ~]# docker run -it --name centos7 centos:7

#进入到容器中,按+退出并停止容器,#按+退出但 不停止容器

#重新进入容器

[root@docker ~]# docker attach centos7

#在容器中执行命令

[root@docker ~]# docker exec -it test ifconfig

[root@docker-nodde1 ~]# docker ps 查看当前运行容器

[root@docker-nodde1 ~]# docker ps -a 查看所有容器

[root@docker-nodde1 ~]# docker inspect busybox 查看容器运行的详细信息
[root@docker-nodde1 ~]# docker start busybox

[root@docker-nodde1 ~]# docker stop busybox

[root@docker-nodde1 ~]# docker kill busybox
[root@docker-nodde1 ~]# docker rm centos7 删除停止的容器

[root@docker-nodde1 ~]# docker rm -f busybox 删除运行的容器

[root@docker-nodde1 ~]# docker container prune -f 删除所有停止的容器
[root@docker-nodde1 ~]# docker run -it --name test busybox

[root@docker-nodde1 ~]# docker rm test

[root@docker-nodde1 ~]# docker run -it --name test busybox #文件后不存在

[root@docker-nodde1 ~]# docker cp test:/bwmis /mnt 把容器中的文件复制到本机

[root@docker-node1 ~]# docker cp /etc/fstab test:/fstab #把本机文件复制到容器中

查看容器内部日志

[root@docker-nodde1 ~]# docker run --name web -d nginx

[root@docker-nodde1 ~]# docker logs web

docker 镜像结构

[root@docker-nodde1 ~]# mkdir docker/

[root@docker-nodde1 ~]# cd docker/

[root@docker-nodde1 docker]# touch file

[root@docker-nodde1 docker]# vim Dockerfile

FROM busybox:latest

MAINTAINER yu@bwmis.org

COPY file /

[root@docker-nodde1 docker]# docker build -t busybox:v1 .

[root@docker-nodde1 docker]# touch file{1..}

[root@docker-nodde1 docker]# tar zcf file.gz file*

[root@docker-nodde1 docker]# vim Dockerfile

FROM busybox:latest

MAINTAINER yu@bwmis.org

COPY file /

ADD file.gz /
[root@docker-nodde1 docker]# vim Dockerfile

[root@docker-nodde1 docker]# docker build -t busybox:v3 .

FROM busybox:latest

MAINTAINER yu@bwmis.org

ENV NAME bwmis

CMD echo $NAM

[root@docker-nodde1 docker]# vim Dockerfile

FROM busybox:latest

MAINTAINER yu@bwmis.org

ENV NAME bwmis

CMD ["/bin/echo", "$NAME"]

[root@docker-nodde1 docker]# docker build -t busybox:v4 .

[root@docker-nodde1 docker]# vim Dockerfile

FROM busybox:latest

MAINTAINER yu@bwmis.org

ENV NAME bwmis

CMD ["/bin/sh", "-c", "/bin/echo $NAME"]

[root@docker-nodde1 docker]# docker build -t busybox:v5 .

[root@docker-nodde1 docker]# vim Dockerfile

FROM busybox:latest

MAINTAINER yu@bwmis.org

ENV NAME bwmis

ENTRYPOINT echo $NAM

[root@docker-nodde1 docker]# docker build -t busybox:v6 .

[root@docker-nodde1 docker]# vim Dockerfile

FROM busybox:latest

MAINTAINER yu@bwmis.org

ENV NAME bwmis

EXPOSE 80 443

VOLUME /var/www/html

WORKDIR /var/www/html

RUN touch file

[root@docker-nodde1 docker]# docker build -t busybox:v7 .

Dockerfile实例

[root@docker-nodde1 ~]# mkdir docker

[root@docker-nodde1 ~]# cd docker/

[root@docker-nodde1 docker]# cp /root/nginx-1.26.1.tar.gz .

[root@docker-nodde1 docker]# vim Dockerfile

FROM centos:7

ADD nginx-1.26.1.tar.gz /mnt

WORKDIR /mnt/nginx-1.26.1

RUN rm -rf /etc/yum.repos.d/*

ADD aliyun.repo /etc/yum.repos.d/aliyun.repo

RUN yum install -y gcc make pcre-devel openssl-devel

RUN ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module

RUN make

RUN make install

EXPOSE 80 443

VOLUME ["/usr/local/nginx/html"]

CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]

[root@docker-nodde1 docker]# docker build -t centos:v1 . 生成镜像

测试镜像可用性

查看容器详情

镜像优化方案

方法1缩减镜像层

[root@docker-nodde1 docker]# vim Dockerfile

FROM centos:7

ADD nginx-1.26.1.tar.gz /mnt

WORKDIR /mnt/nginx-1.26.1

RUN rm -rf /etc/yum.repos.d/*

ADD aliyun.repo /etc/yum.repos.d/aliyun.repo

RUN yum install -y gcc make pcre-devel openssl-devel && ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module && make && make install && yum clean all

EXPOSE 80

VOLUME ["/usr/local/nginx/html"]

CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]

[root@docker-nodde1 docker]# docker build -t centos:v2 .

FROM centos:7

ADD nginx-1.26.1.tar.gz /mnt

WORKDIR /mnt/nginx-1.26.1

RUN rm -rf /etc/yum.repos.d/*

ADD aliyun.repo /etc/yum.repos.d/aliyun.repo

RUN yum install -y gcc make pcre-devel openssl-devel

RUN ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module

RUN make

RUN make install

RUN yum clean all

EXPOSE 80 443

VOLUME ["/usr/local/nginx/html"]

CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]

方法2 多阶段构建

[root@docker-nodde1 docker]# vim Dockerfile

FROM centos:7 as build

ADD nginx-1.26.1.tar.gz /mnt

WORKDIR /mnt/nginx-1.26.1

RUN rm -rf /etc/yum.repos.d/*

ADD aliyun.repo /etc/yum.repos.d/aliyun.repo

RUN yum install -y gcc make pcre-devel openssl-devel && ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module && make && make install && yum clean all

FROM centos:7

COPY --from=build /usr/local/nginx /usr/local/nginx

EXPOSE 80

VOLUME ["/usr/local/nginx/html"]

CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]

[root@docker-nodde1 docker]# docker build -t centos:v3 .

方法3:使用最精简镜像

[root@docker-nodde1 docker.service.d]# docker pull gcr.io/distroless/base

[root@docker-nodde1 new]# pwd

/root/new

[root@docker-nodde1 new]# vim Dockerfile

FROM nginx:latest as base

RUN mkdir -p /opt/var/cache/nginx && \

cp -a --parents /usr/lib/nginx /opt && \

cp -a --parents /usr/share/nginx /opt && \

cp -a --parents /var/log/nginx /opt && \

cp -aL --parents /var/run /opt && \

cp -a --parents /etc/nginx /opt && \

cp -a --parents /etc/passwd /opt && \

cp -a --parents /etc/group /opt && \

cp -a --parents /usr/sbin/nginx /opt && \

cp -a --parents /usr/sbin/nginx-debug /opt && \

cp -a --parents /lib/x86_64-linux-gnu/ld-* /opt && \

cp -a --parents /usr/lib/x86_64-linux-gnu/libpcre* /opt && \

cp -a --parents /lib/x86_64-linux-gnu/libz.so.* /opt && \

cp -a --parents /lib/x86_64-linux-gnu/libc* /opt && \

cp -a --parents /lib/x86_64-linux-gnu/libdl* /opt && \

cp -a --parents /lib/x86_64-linux-gnu/libpthread* /opt && \

cp -a --parents /lib/x86_64-linux-gnu/libcrypt* /opt && \

cp -a --parents /usr/lib/x86_64-linux-gnu/libssl.so.* /opt && \

cp -a --parents /usr/lib/x86_64-linux-gnu/libcrypto.so.* /opt && \

cp /usr/share/zoneinfo/${TIME_ZONE:-ROC} /opt/etc/localtime

FROM gcr.io/distroless/base-debian11

COPY --from=base /opt /

EXPOSE 80 443

ENTRYPOINT ["nginx", "-g", "daemon off;"]

[root@docker-nodde1 new]# docker build -t nginx:v4 .

docker镜像仓库的管理

docker hub的使用方法

[root@docker-nodde1 docker]# docker login

[root@docker ~]# cd .docker/

[root@docker .docker]# ls config.json

[root@docker .docker]# cat config.json

[root@docker ~]# docker tag gcr.io/distroless/base-debian11:latest timinglee/base-debian11:latest

[root@docker ~]# docker push timinglee/base-debian11:latest

搭建简单的Registry仓库

下载Registry镜像

[root@docker-nodde1 docker]# docker pull registry

[root@docker-nodde1 docker]# docker run -d -p 5000:5000 registry:latest

[root@docker-nodde1 docker]# docker push 172.25.250.100:5000/busybox:latest

[root@docker-nodde1 docker]# vim /etc/docker/daemon.json

{

"registry-mirrors": ["https://docker.m.daocloud.io"],

"insecure-registries" : ["172.25.250.100:5000"]

}

[root@docker-nodde1 ~]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout certs/yunan.key \

> -addext "subjectAltName = DNS:bwmis.org" \

> -x509 -days 365 -out certs/yunan.crt

[root@docker-nodde1 ~]# docker run -d -p 443:443 --restart=always --name registry \

> --name registry -v /opt/registry:/var/lib/registry \

> -v /root/certs:/certs \

> -e REGISTRY_HTTP_ADDR=0.0.0.0:443 \

> -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/yunan.crt \

> -e REGISTRY_HTTP_TLS_KEY=/certs/yunan.key registry

c3a5e73b65af493bcb8e7caa1285f60abb8789542bb6d52b9a63ad5dff1cd4c0

[root@docker-nodde1 ~]# docker push bwmis.org/busybox:latest

The push refers to repository [bwmis.org/busybox]

Get "https://bwmis.org/v2/": tls: failed to verify certificate: x509: certificate signed by unknown authority

[root@docker-nodde1 ~]# mkdir /etc/docker/certs.d/bwmis.org/ -p

[root@docker-nodde1 ~]# cp /root/certs/yunan.crt /etc/docker/certs.d/bwmis.org/ca.crt

[root@docker-nodde1 ~]# docker push bwmis.org/busybox:latest

The push refers to repository [bwmis.org/busybox]

d51af96cf93e: Pushed

latest: digest: sha256:28e01ab32c9dbcbaae96cf0d5b472f22e231d9e603811857b295e61197e40a9b size: 527

root@docker-nodde1 ~]# mkdir auth

[root@docker-nodde1 ~]# htpasswd -Bc auth/htpasswd yunan

New password:

Re-type new password:

Adding password for user yunan

[root@docker-nodde1 ~]# docker run -d -p 443:443 --restart=always --name registry --name registry -v /opt/registry:/var/lib/registry -v /root/certs:/certs -e REGISTRY_HTTP_ADDR=0.0.0.0:443 -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/yunan.crt -e REGISTRY_HTTP_TLS_KEY=/certs/yunan.key -v /root/auth:/auth -e "REGISTRY_AUTH=htpasswd" -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd registry

71248be6991b70e7c47c85c1a6870db84dd99f4a87072efdcf18b901f9a9545a

[root@docker-nodde1 ~]# curl -k https://bwmis.org/v2/_catalog -u yunan:123

{"repositories":["busybox"]}

[root@docker-nodde1 ~]# docker login bwmis.org

Username: yunan

Password:

WARNING! Your password will be stored unencrypted in /root/.docker/config.json.

Configure a credential helper to remove this warning. See

https://docs.docker.com/engine/reference/commandline/login/#credential-stores

Login Succeeded

[root@docker-nodde1 ~]# docker push bwmis.org/busybox

Using default tag: latest

The push refers to repository [bwmis.org/busybox]

d51af96cf93e: Layer already exists

latest: digest: sha256:28e01ab32c9dbcbaae96cf0d5b472f22e231d9e603811857b295e61197e40a9b size: 527

#没有登录的时候

[root@docker-nodde1 ~]# cd .docker/

[root@docker-nodde1 .docker]# rm -rf config.json

[root@docker-nodde1 .docker]# docker push bwmis.org/busybox

[root@docker ~]# tar zxf harbor-offline-installer-v2.5.4.tgz

[root@docker ~]# cd harbor/

[root@docker harbor]# cp harbor.yml.tmpl harbor.yml

[root@docker harbor]# vim harbor.yml

[root@docker harbor]# ./install.sh --with-chartmuseum

[root@docker-nodde1 harbor]# docker tag nginx:v4 bwmis.org/11/nginx:v4

[root@docker-nodde1 harbor]# docker push bwmis.org/11/nginx:v4

Docker 网络

docker安装后会自动创建3种网络:bridge、host、none

host网络模式需要在容器创建时指定 --network=host host模式可以让容器共享宿主机网络栈,这样的好处是外部主机与容器直接通信,但是容器的网络缺少 隔离性

none模式是指禁用网络功能,只有lo接口,在容器创建时使用--network=none指定。

[root@docker-nodde1 ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
aa477a58e8e3   bridge    bridge    local
c00a12b2f926   host      host      local
626b29d5cd2c   none      null      local

[root@docker-nodde1 ~]# docker run -d --name web -p 80:80 nginx:1.23 
f15735a549e8b6987425fc10c56bf3490820bc1bda298a1b80ed8ef6a8225b89
[root@docker-nodde1 ~]# ifconfig 
docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:88ff:fe46:58b9  prefixlen 64  scopeid 0x20<link>
        ether 02:42:88:46:58:b9  txqueuelen 0  (Ethernet)
        RX packets 1049  bytes 197841 (193.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1381  bytes 6814555 (6.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.25.250.100  netmask 255.255.255.0  broadcast 172.25.250.255
        inet6 fe80::f058:d57f:1866:cda1  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:88:e1:3e  txqueuelen 1000  (Ethernet)
        RX packets 818475  bytes 1114817333 (1.0 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 187350  bytes 26201558 (24.9 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 9739  bytes 1071513 (1.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 9739  bytes 1071513 (1.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

veth223eeb5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet6 fe80::78a0:c0ff:fe9a:373a  prefixlen 64  scopeid 0x20<link>
        ether 7a:a0:c0:9a:37:3a  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 8  bytes 736 (736.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
[root@docker-nodde1 ~]# docker network inspect bridge 
[
    {
        "Name": "bridge",
        "Id": "aa477a58e8e39023d0cb10df274e720e52248ddf95764549c3311a974f7e5162",
        "Created": "2024-08-28T16:00:16.436592977+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "f15735a549e8b6987425fc10c56bf3490820bc1bda298a1b80ed8ef6a8225b89": {
                "Name": "web",
                "EndpointID": "f955a99923cc6d24fd2354d6d50fab6ba5be66dbafbc4688002983b29c547b1a",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
[root@docker-nodde1 ~]# 
[root@docker-nodde1 ~]# docker run -it --name test --network host busybox
/ # ifconfig
docker0   Link encap:Ethernet  HWaddr 02:42:88:46:58:B9  
          inet addr:172.17.0.1  Bcast:172.17.255.255  Mask:255.255.0.0
          inet6 addr: fe80::42:88ff:fe46:58b9/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1049 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1381 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:197841 (193.2 KiB)  TX bytes:6814555 (6.4 MiB)

eth0      Link encap:Ethernet  HWaddr 00:0C:29:88:E1:3E  
          inet addr:172.25.250.100  Bcast:172.25.250.255  Mask:255.255.255.0
          inet6 addr: fe80::f058:d57f:1866:cda1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:819016 errors:0 dropped:0 overruns:0 frame:0
          TX packets:187682 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1114860207 (1.0 GiB)  TX bytes:26237022 (25.0 MiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:9739 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9739 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1071513 (1.0 MiB)  TX bytes:1071513 (1.0 MiB)

veth223eeb5 Link encap:Ethernet  HWaddr 7A:A0:C0:9A:37:3A  
          inet6 addr: fe80::78a0:c0ff:fe9a:373a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:13 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:1086 (1.0 KiB)

/ # 
/ # exit
[root@docker-nodde1 ~]# docker run -it --name test --rm  --network none busybox
/ # ifconfig 
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

/ # exit
[root@docker-nodde1 ~]# docker network create my_net1
04d5a7f838e04df45eb74c6296eb7f74c1b303d63271d8d0fd14616f3e664ce8
[root@docker-nodde1 ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
aa477a58e8e3   bridge    bridge    local
c00a12b2f926   host      host      local
04d5a7f838e0   my_net1   bridge    local
626b29d5cd2c   none      null      local
[root@docker-nodde1 ~]# ifconfig 
br-04d5a7f838e0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.18.0.1  netmask 255.255.0.0  broadcast 172.18.255.255
        ether 02:42:49:d2:47:b6  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 14  bytes 1156 (1.1 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:88ff:fe46:58b9  prefixlen 64  scopeid 0x20<link>
        ether 02:42:88:46:58:b9  txqueuelen 0  (Ethernet)
        RX packets 1049  bytes 197841 (193.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1381  bytes 6814555 (6.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.25.250.100  netmask 255.255.255.0  broadcast 172.25.250.255
        inet6 fe80::f058:d57f:1866:cda1  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:88:e1:3e  txqueuelen 1000  (Ethernet)
        RX packets 819332  bytes 1114885699 (1.0 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 187879  bytes 26258512 (25.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 9739  bytes 1071513 (1.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 9739  bytes 1071513 (1.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

veth223eeb5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet6 fe80::78a0:c0ff:fe9a:373a  prefixlen 64  scopeid 0x20<link>
        ether 7a:a0:c0:9a:37:3a  txqueuelen 0  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 14  bytes 1156 (1.1 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

桥接也支持自定义子网和网关

bash 复制代码
[root@docker-nodde1 ~]# docker network create my_net2 --subnet 192.168.0.0/24 --gateway 192.168.0.100
4c51759c0a359e63847168c4c4703bf04962f34aaea81eecf4205d0a266425fb
[root@docker-nodde1 ~]# docker network inspect my_net2
[
    {
        "Name": "my_net2",
        "Id": "4c51759c0a359e63847168c4c4703bf04962f34aaea81eecf4205d0a266425fb",
        "Created": "2024-08-28T16:19:59.98430493+08:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "192.168.0.0/24",
                    "Gateway": "192.168.0.100"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
[root@docker-nodde1 ~]# docker run -d --name web1 nginx
640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb
[root@docker-nodde1 ~]# docker run -d --name web2 nginx
8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680
[root@docker-nodde1 ~]# docker inspect web1
[
    {
        "Id": "640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb",
        "Created": "2024-08-28T08:20:32.650093821Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 62832,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2024-08-28T08:20:32.669915265Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5ef79149e0ec84a7a9f9284c3f91aa3c20608f8391f5445eabe92ef07dbda03c",
        "ResolvConfPath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/hostname",
        "HostsPath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/hosts",
        "LogPath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb-json.log",
        "Name": "/web1",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "bridge",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                22,
                138
            ],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": [],
            "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",
                "/sys/devices/virtual/powercap"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170-init/diff:/var/lib/docker/overlay2/46518f60523f5de1712cf98fdda126920a26573147dd56bb8e6be811742f48e0/diff:/var/lib/docker/overlay2/23f652d62523d907648a30fe074369cf8a8ac3d49ab88856f754ecb35651d75c/diff:/var/lib/docker/overlay2/e60d236ef625abb2570a33d15ed12a61c4e8ae39381fa16d4f5e5f286bb3e9b5/diff:/var/lib/docker/overlay2/c7e43220d0aad034c756f8e93329c63fbda1ea050613b674036d57a21f984422/diff:/var/lib/docker/overlay2/ce2ad29319d7a60ab206ce43f34c37c18e1674bb6df3eab3fce69a5579db1c11/diff:/var/lib/docker/overlay2/392c910bcefd9f8e43411e92004107e5e22988e1648133056a1a72ef732c56ba/diff:/var/lib/docker/overlay2/f90e253597009ff908369ae64d7c357e7a44f87e2f7760fb9930ea0f1c9edf53/diff",
                "MergedDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170/merged",
                "UpperDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170/diff",
                "WorkDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "640ef8c65945",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.27.1",
                "NJS_VERSION=0.8.5",
                "NJS_RELEASE=1~bookworm",
                "PKG_RELEASE=1~bookworm",
                "DYNPKG_RELEASE=2~bookworm"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "bee79687b72f0edd3cba92fc5d363864d9387b279e5a0e06f7e26d4df5653c83",
            "SandboxKey": "/var/run/docker/netns/bee79687b72f",
            "Ports": {
                "80/tcp": null
            },
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "dc44a555e8ca3d0a2cbfe8fea66c9b6762c72af6eefdd750f2aa26e7f2c16cc3",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null,
                    "NetworkID": "aa477a58e8e39023d0cb10df274e720e52248ddf95764549c3311a974f7e5162",
                    "EndpointID": "dc44a555e8ca3d0a2cbfe8fea66c9b6762c72af6eefdd750f2aa26e7f2c16cc3",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DNSNames": null
                }
            }
        }
    }
]
[root@docker-nodde1 ~]# docker inspect web2
[
    {
        "Id": "8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680",
        "Created": "2024-08-28T08:20:35.941429684Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 62946,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2024-08-28T08:20:35.972099276Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5ef79149e0ec84a7a9f9284c3f91aa3c20608f8391f5445eabe92ef07dbda03c",
        "ResolvConfPath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/hostname",
        "HostsPath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/hosts",
        "LogPath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680-json.log",
        "Name": "/web2",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "bridge",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                22,
                138
            ],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": [],
            "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",
                "/sys/devices/virtual/powercap"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d-init/diff:/var/lib/docker/overlay2/46518f60523f5de1712cf98fdda126920a26573147dd56bb8e6be811742f48e0/diff:/var/lib/docker/overlay2/23f652d62523d907648a30fe074369cf8a8ac3d49ab88856f754ecb35651d75c/diff:/var/lib/docker/overlay2/e60d236ef625abb2570a33d15ed12a61c4e8ae39381fa16d4f5e5f286bb3e9b5/diff:/var/lib/docker/overlay2/c7e43220d0aad034c756f8e93329c63fbda1ea050613b674036d57a21f984422/diff:/var/lib/docker/overlay2/ce2ad29319d7a60ab206ce43f34c37c18e1674bb6df3eab3fce69a5579db1c11/diff:/var/lib/docker/overlay2/392c910bcefd9f8e43411e92004107e5e22988e1648133056a1a72ef732c56ba/diff:/var/lib/docker/overlay2/f90e253597009ff908369ae64d7c357e7a44f87e2f7760fb9930ea0f1c9edf53/diff",
                "MergedDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d/merged",
                "UpperDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d/diff",
                "WorkDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "8050af87f123",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.27.1",
                "NJS_VERSION=0.8.5",
                "NJS_RELEASE=1~bookworm",
                "PKG_RELEASE=1~bookworm",
                "DYNPKG_RELEASE=2~bookworm"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "66e3c584e4c8614183b914325595f0193963c757d450230edcbc9f6da79d347e",
            "SandboxKey": "/var/run/docker/netns/66e3c584e4c8",
            "Ports": {
                "80/tcp": null
            },
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "b2df049cf7bdfde380e9d0591dacc2a1cc22e31bce7af298635e39f10cff2a76",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.4",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:04",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "MacAddress": "02:42:ac:11:00:04",
                    "DriverOpts": null,
                    "NetworkID": "aa477a58e8e39023d0cb10df274e720e52248ddf95764549c3311a974f7e5162",
                    "EndpointID": "b2df049cf7bdfde380e9d0591dacc2a1cc22e31bce7af298635e39f10cff2a76",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DNSNames": null
                }
            }
        }
    }
]
#关闭容器后重启容器,启动顺序调换
[root@docker-nodde1 ~]# docker stop web1 web2
web1
web2
[root@docker-nodde1 ~]# docker start web2
web2
[root@docker-nodde1 ~]# docker start web1
web1
[root@docker-nodde1 ~]# docker inspect web1
[
    {
        "Id": "640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb",
        "Created": "2024-08-28T08:20:32.650093821Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 63498,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2024-08-28T08:21:58.48231375Z",
            "FinishedAt": "2024-08-28T08:21:48.570190321Z"
        },
        "Image": "sha256:5ef79149e0ec84a7a9f9284c3f91aa3c20608f8391f5445eabe92ef07dbda03c",
        "ResolvConfPath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/hostname",
        "HostsPath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/hosts",
        "LogPath": "/var/lib/docker/containers/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb/640ef8c659451419d32bdf7632333c710ed5179e9e77855f681e1144980b68eb-json.log",
        "Name": "/web1",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "bridge",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                22,
                138
            ],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": [],
            "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",
                "/sys/devices/virtual/powercap"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170-init/diff:/var/lib/docker/overlay2/46518f60523f5de1712cf98fdda126920a26573147dd56bb8e6be811742f48e0/diff:/var/lib/docker/overlay2/23f652d62523d907648a30fe074369cf8a8ac3d49ab88856f754ecb35651d75c/diff:/var/lib/docker/overlay2/e60d236ef625abb2570a33d15ed12a61c4e8ae39381fa16d4f5e5f286bb3e9b5/diff:/var/lib/docker/overlay2/c7e43220d0aad034c756f8e93329c63fbda1ea050613b674036d57a21f984422/diff:/var/lib/docker/overlay2/ce2ad29319d7a60ab206ce43f34c37c18e1674bb6df3eab3fce69a5579db1c11/diff:/var/lib/docker/overlay2/392c910bcefd9f8e43411e92004107e5e22988e1648133056a1a72ef732c56ba/diff:/var/lib/docker/overlay2/f90e253597009ff908369ae64d7c357e7a44f87e2f7760fb9930ea0f1c9edf53/diff",
                "MergedDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170/merged",
                "UpperDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170/diff",
                "WorkDir": "/var/lib/docker/overlay2/58f2241c2cb3d19863d634db0d7d3319c9ae431bdcca250f1a529f6b1efcc170/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "640ef8c65945",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.27.1",
                "NJS_VERSION=0.8.5",
                "NJS_RELEASE=1~bookworm",
                "PKG_RELEASE=1~bookworm",
                "DYNPKG_RELEASE=2~bookworm"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "6bcdb5f9863d61f918333fc6f3a575e213f0571ea12033bf0f28577c777ecd9b",
            "SandboxKey": "/var/run/docker/netns/6bcdb5f9863d",
            "Ports": {
                "80/tcp": null
            },
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "cf0c6e39895c9a800dfe2e4f558014803053f4092750235ec93399ea1cf81e48",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.4",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:04",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "MacAddress": "02:42:ac:11:00:04",
                    "DriverOpts": null,
                    "NetworkID": "aa477a58e8e39023d0cb10df274e720e52248ddf95764549c3311a974f7e5162",
                    "EndpointID": "cf0c6e39895c9a800dfe2e4f558014803053f4092750235ec93399ea1cf81e48",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DNSNames": null
                }
            }
        }
    }
]
[root@docker-nodde1 ~]# docker inspect web2
[
    {
        "Id": "8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680",
        "Created": "2024-08-28T08:20:35.941429684Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 63407,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2024-08-28T08:21:57.220696125Z",
            "FinishedAt": "2024-08-28T08:21:48.570774461Z"
        },
        "Image": "sha256:5ef79149e0ec84a7a9f9284c3f91aa3c20608f8391f5445eabe92ef07dbda03c",
        "ResolvConfPath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/hostname",
        "HostsPath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/hosts",
        "LogPath": "/var/lib/docker/containers/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680/8050af87f12304b138ff859f9ae9bb7163b29236dce45a903ad45873ccb3c680-json.log",
        "Name": "/web2",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "bridge",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "ConsoleSize": [
                22,
                138
            ],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "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",
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": [],
            "BlkioDeviceWriteBps": [],
            "BlkioDeviceReadIOps": [],
            "BlkioDeviceWriteIOps": [],
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": [],
            "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",
                "/sys/devices/virtual/powercap"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d-init/diff:/var/lib/docker/overlay2/46518f60523f5de1712cf98fdda126920a26573147dd56bb8e6be811742f48e0/diff:/var/lib/docker/overlay2/23f652d62523d907648a30fe074369cf8a8ac3d49ab88856f754ecb35651d75c/diff:/var/lib/docker/overlay2/e60d236ef625abb2570a33d15ed12a61c4e8ae39381fa16d4f5e5f286bb3e9b5/diff:/var/lib/docker/overlay2/c7e43220d0aad034c756f8e93329c63fbda1ea050613b674036d57a21f984422/diff:/var/lib/docker/overlay2/ce2ad29319d7a60ab206ce43f34c37c18e1674bb6df3eab3fce69a5579db1c11/diff:/var/lib/docker/overlay2/392c910bcefd9f8e43411e92004107e5e22988e1648133056a1a72ef732c56ba/diff:/var/lib/docker/overlay2/f90e253597009ff908369ae64d7c357e7a44f87e2f7760fb9930ea0f1c9edf53/diff",
                "MergedDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d/merged",
                "UpperDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d/diff",
                "WorkDir": "/var/lib/docker/overlay2/291b39e234112430d1dae3435f106a60583bb354ec5f0925e5e0cc34c42fab4d/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "8050af87f123",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.27.1",
                "NJS_VERSION=0.8.5",
                "NJS_RELEASE=1~bookworm",
                "PKG_RELEASE=1~bookworm",
                "DYNPKG_RELEASE=2~bookworm"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGQUIT"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "95b844592e6f808ab85b6af09415d132b74bbdc4094a604b3f40c1bc79469875",
            "SandboxKey": "/var/run/docker/netns/95b844592e6f",
            "Ports": {
                "80/tcp": null
            },
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "316290a60eaae958bc6d774be9604ccd81bc59c2f1d607edecaa7381f5b85d73",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null,
                    "NetworkID": "aa477a58e8e39023d0cb10df274e720e52248ddf95764549c3311a974f7e5162",
                    "EndpointID": "316290a60eaae958bc6d774be9604ccd81bc59c2f1d607edecaa7381f5b85d73",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "DNSNames": null
                }
            }
        }
    }
]
[root@docker-nodde1 ~]# docker run -d --network my_net1 --name web nginx
docker: Error response from daemon: Conflict. The container name "/web" is already in use by container "f15735a549e8b6987425fc10c56bf3490820bc1bda298a1b80ed8ef6a8225b89". You have to remove (or rename) that container to be able to reuse that name.
See 'docker run --help'.
[root@docker-nodde1 ~]# docker rm -f f15735a549e8b6987425fc10c56bf3490820bc1bda298a1b80ed8ef6a8225b89
f15735a549e8b6987425fc10c56bf3490820bc1bda298a1b80ed8ef6a8225b89
[root@docker-nodde1 ~]# docker run -d --network my_net1 --name web nginx
d01f643e8265db8d08e924ac55cd33d89e7480db497e351e81b4a787af9a1df0
[root@docker-nodde1 ~]# docker run -it --network my_net1 --name test busybox
/ # ping web
PING web (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.135 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.129 ms
64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.075 ms
^C
--- web ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 0.075/0.113/0.135 ms
/ # 

#在rhel7中使用的是iptables进行网络隔离,在rhel9中使用nftpables

[root@docker ~]# nft list ruleset可以看到网络隔离策略

让不同的自定义网络互通

[root@docker-nodde1 ~]# docker run -d --name web1 --network my_net1 nginx

df4d21f87be6985927ae5565191d79050a41daf562c91f363aa5c4d331669b1f

[root@docker-nodde1 ~]# docker run -it --name test --network my_net2 busybox

/ # ifconfig

eth0 Link encap:Ethernet HWaddr 02:42:C0:A8:00:01

inet addr:192.168.0.1 Bcast:192.168.0.255 Mask:255.255.255.0

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:12 errors:0 dropped:0 overruns:0 frame:0

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:1112 (1.0 KiB) TX bytes:0 (0.0 B)

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:65536 Metric:1

RX packets:0 errors:0 dropped:0 overruns:0 frame:0

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

/ # ping 172.18.0.2

PING 172.18.0.2 (172.18.0.2): 56 data bytes

^C

--- 172.18.0.2 ping statistics ---

9 packets transmitted, 0 packets received, 100% packet loss

/ # exit

[root@docker-nodde1 ~]# docker network connect my_net1 test #加入网络eth1

[root@docker-nodde1 ~]# docker exec -it test /bin/sh

/ # ifconfig

eth0 Link encap:Ethernet HWaddr 02:42:AC:12:00:04

inet addr:172.18.0.4 Bcast:172.18.255.255 Mask:255.255.0.0

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:8 errors:0 dropped:0 overruns:0 frame:0

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:656 (656.0 B) TX bytes:0 (0.0 B)

eth1 Link encap:Ethernet HWaddr 02:42:C0:A8:00:01

inet addr:192.168.0.1 Bcast:192.168.0.255 Mask:255.255.255.0

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:10 errors:0 dropped:0 overruns:0 frame:0

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:876 (876.0 B) TX bytes:0 (0.0 B)

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:65536 Metric:1

RX packets:0 errors:0 dropped:0 overruns:0 frame:0

TX packets:0 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

/ # ping 172.18.0.2

PING 172.18.0.2 (172.18.0.2): 56 data bytes

64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.117 ms

64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.110 ms

joined容器

Joined容器一种较为特别的网络模式,•在容器创建时使用--network=container:vm1指定。(vm1指定 的是运行的容器名) 处于这个模式下的 Docker 容器会共享一个网络栈,这样两个容器之间可以使用localhost高效快速通信

bash 复制代码
[root@docker-nodde1 ~]# docker run -it --rm  --network container:web1 busybox
/ # ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:AC:12:00:03  
          inet addr:172.18.0.3  Bcast:172.18.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:15 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:1118 (1.0 KiB)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

/ # exit
[root@docker-nodde1 ~]# docker run -it --rm --network container:web1 centos:7
[root@df4d21f87be6 /]# curl  localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

[root@docker-nodde1 ~]# docker pull phpmyadmin:latest

[root@docker-nodde1 ~]# docker pull mysql:5.7
[root@docker-nodde1 ~]# docker run -d --name mysqladmin --network my_net1 \

> -e PMA_ARBITRARY=1 \ #在web页面中可以手动输入数据库地址和端口

> -p 80:80 phpmyadmin:latest

de3b027e3dfcb79b2a845ae2c3356c31d7823d49823bfa31187ce0f4437ac7ed

[root@docker-nodde1 ~]# docker run -d --name mysql \

> -e MYSQL_ROOT_RASSWORD='lee' \ #设定数据库密码

> --network container:mysqladmin \ #把数据库容器添加到phpmyadmin容器中

> mysql:5.7

dbed323fd1d62f3475a8f91d4aa465438fcd370943938f5c66d831ec0c00bd84

容器访问外网

#通过docker-proxy对数据包进行内转

[root@docker-nodde1 ~]# docker run -d --name webserver -p 80:80 nginx

[root@docker-nodde1 ~]# iptables -t nat -nL

macvlan网络方式实现跨主机通信

macvlan会独占主机网卡,但可以使用vlan子接口实现多macvlan网络 俩个网卡有一个仅主机
[root@docker-nodde1 ~]# ip link set eth1 promisc on

[root@docker-nodde1 ~]# ip link set up eth1

[root@docker-nodde1 ~]# ifconfig eth1

[root@docker-nodde1 ~]# docker network create \

> -d macvlan \

> --subnet 2.2.2.0/24 \

> --gateway 2.2.2.2 \

> -o parent=eth1 vlan1

当其中一个退出后

[root@docker-nodde1 ~]# docker run -it --rm -v /tmp/data1:/data1 \

> -v /tmp/data1:/data2:ro \

> -v /etc/passwd:/data/passwd:ro busybox

/ # tail -n 3 /data/passwd

pipewire:x:995:991:PipeWire System Daemon:/run/pipewire:/usr/sbin/nologin

geoclue:x:994:990:User for geoclue:/var/lib/geoclue:/sbin/nologin

flatpak:x:993:989:User for flatpak system helper:/:/sbin/nologin

/ # touch /data1/file1

/ # touch /data2/file1

touch: /data2/file1: Read-only file system

默认创建的数据卷目录都在 /var/lib/docker/volumes 中

[root@docker-nodde1 ~]# docker run -d --name mysql -e MYSQL_ROOT_PASSWORD='123' mysql:5.7

4728dd966e34e8c4c2df8414350b10d4af1a7971531990e766833badacfd13ee

清理微使用的Docker数据卷

[root@docker-nodde1 ~]# docker volume prune

建立数据卷

[root@docker-nodde1 ~]# docker volume create lee
lee

[root@docker-nodde1 ~]# ls -l /var/lib/docker/volumes/lee/_data/

total 0

使用建立的数据卷

[root@docker-nodde1 ~]# docker run -d --name web3 -p 80:80 -v lee:/usr/share/nginx/html nginx

d7a89f8a86ec735be79e911d876998bef677d614cf9fa0ba5836466604a4ed21

[root@docker-nodde1 ~]# cd /var/lib/docker/volumes/lee/_data/

[root@docker-nodde1 _data]# ls

50x.html index.html

[root@docker-nodde1 _data]# echo lee >index.html

[root@docker-nodde1 _data]# curl 172.25.250.100

lee

数据卷容器

1.建立数据卷容器

[root@docker-nodde1 ~]# docker run -d --name datavol \

> -v /tmp/data1:/data1:rw \

> -v /tmp/data2:/data2:ro \

> -v /etc/resolv.conf:/etc/hosts busybox

14d531ed29a6046ec4d27598c19d0ad84248b2adcffe083a418fdba4ec846939

[root@docker-nodde1 ~]# docker run -it --name tes --rm --volumes-from datavol busybox

备份与迁移数据卷

[root@docker-nodde1 ~]# docker run --volumes-from datavol -v `pwd`:/backup busybox tar zcf /backup/data1.tar.gz data1

[root@docker-nodde1 ~]# docker run -it --name te -v lee:/data1 -v 'pwd':/backup busybox /bin/sh -c "tar zxf /backup/data1.tar.gz;/bin/sh"

安全性

[root@docker-nodde1 ~]# grubby --update-kernel=/boot/vmlinuz-$(uname -r) \

> --args="systemd.unified_cgroup_hierachy=0 systemd.legacy_systemd_cgroup_controller"

[root@docker-nodde1 ~]# mount -t cgroup

[root@docker-nodde1 ns]# docker run -d --name web nginx

f33fcc3ec1079f29f2eb42001bd0d658f34bcc8b41bd4567e5f3dfb3c53447da

[root@docker-nodde1 ns]# docker inspect web | grep Pid

"Pid": 3870,

"PidMode": "",

"PidsLimit": null,

隔离

[root@docker-nodde1 ~]# ls -ld /var/lib/docker/ #默认docker是用root用户控制资源的

drwx--x--- 12 root root 171 Aug 30 15:18 /var/lib/docker/

Docker的资源限制

Linux Cgroups 的全称是 Linux Control Group。

[root@docker-nodde1 ~]# mount -t cgroup

cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd)

cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)

cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)

cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)

cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)

cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)

cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)

cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)

cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)

cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)

cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)

cgroup on /sys/fs/cgroup/misc type cgroup (rw,nosuid,nodev,noexec,relatime,misc)

cgroup on /sys/fs/cgroup/rdma type cgroup (rw,nosuid,nodev,noexec,relatime,rdma)

[root@docker-nodde1 ns]# docker run -it --rm --name test1 --cpu-period 100000 \

> --cpu-quota 20000 ubuntu

root@a00b77981549:/# dd if=/dev/zero of=/dev/null &

[1] 9

root@a00b77981549:/# cat /sys/fs/cgroup/cpu/cpu.cfs_period_us

100000

root@a00b77981549:/# cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us

20000

[root@docker-nodde1 ns]# echo 0 > /sys/devices/system/cpu/cpu1/online

[root@docker-nodde1 ns]# cat /proc/cpuinfo

[root@docker-nodde1 ~]# docker run -it --rm --cpu-shares 100 ubuntu

root@fdea6b02e293:/# dd if=/dev/zero of=/dev/null &

限制内存使用

#开启容器并限制容器使用内存大小

[root@docker-nodde1 ~]# docker run -d --name test --memory 200M --memory-swap 200M nginx

f89ab8961da964785a0dc25a6ba4ed3ac5987c11cb277cd9897aa2b8b0ea8f16

#查看容器内存使用限制

[root@docker-nodde1 ~]# docker run -d --name test --memory 200M --memory-swap 200M nginx

f89ab8961da964785a0dc25a6ba4ed3ac5987c11cb277cd9897aa2b8b0ea8f16

[root@docker-nodde1 ~]# cd /sys/fs/cgroup/memory/docker/f89ab8961da964785a0dc25a6ba4ed3ac5987c11cb277cd9897aa2b8b0ea8f16/

[root@docker-nodde1 f89ab8961da964785a0dc25a6ba4ed3ac5987c11cb277cd9897aa2b8b0ea8f16]# cat memory.limit_in_bytes

209715200

[root@docker-nodde1 f89ab8961da964785a0dc25a6ba4ed3ac5987c11cb277cd9897aa2b8b0ea8f16]# cat memory.memsw.limit_in_bytes

209715200

#测试容器内存限制,在容器中我们测试内存限制效果不是很明显,可以利用工具模拟容器在内存中写入数据 #在系统中/dev/shm这个目录被挂在到内存中

[root@docker-nodde1 ~]# docker run -d --name test --rm --memory 200M --memory-swap 200M nginx

[root@docker-nodde1 ~]# cd /sys/fs/cgroup/

记录了150+0 的读入 记录了150+0 的写出

也可以自建控制器

[root@docker-nodde1 ~]# mkdir -p /sys/fs/cgroup/memory/x1/

[root@docker-nodde1 ~]# ls /sys/fs/cgroup/memory/x1/

[root@docker-nodde1 ~]# echo 209715200 > /sys/fs/cgroup/memory/x1/memory.limit_in_bytes #内存可用大小限制

[root@docker-nodde1 ~]# cat /sys/fs/cgroup/memory/x1/tasks

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=100

100+0 records in 记录了100+0 的读入 记录了100+0 的写出

100+0 records out

104857600 bytes (105 MB, 100 MiB) copied, 0.0211774 s, 5.0 GB/s

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=300

300+0 records in

300+0 records out

314572800 bytes (315 MB, 300 MiB) copied, 0.261763 s, 1.2 GB/s

[root@docker-nodde1 ~]# rm -rf /dev/s

sg0 shm/ snapshot snd/ sr0 stderr stdin stdout

[root@docker-nodde1 ~]# rm -rf /dev/shm/bigfile

[root@docker-nodde1 ~]# echo 209715200 > /sys/fs/cgroup/memory/x1/memory.memsw.limit_in_bytes

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=200

Killed

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=199

Killed

[root@docker-nodde1 ~]# rm -rf /dev/shm/bigfile

[root@docker-nodde1 ~]# rm -rf /dev/shm/bigfile

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=180

180+0 records in

180+0 records out

188743680 bytes (189 MB, 180 MiB) copied, 0.0339609 s, 5.6 GB/s

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=190

190+0 records in

190+0 records out

199229440 bytes (199 MB, 190 MiB) copied, 0.0293801 s, 6.8 GB/s

[root@docker-nodde1 ~]# cgexec -g memory:x1 dd if=/dev/zero of=/dev/shm/bigfile bs=1M count=200

Killed

限制docker的磁盘io

[root@docker-nodde1 ~]# docker run -it --rm \

> --device-write-bps \ #指定容器使用磁盘io的速率

> /dev/nvme0n1:30M \ #/dev/nvme0n1是指定系统的磁盘,30M即每秒30M数据

> ubuntu

root@0182e6b37bd5:/# dd if=/dev/zero of=bigfile

^C14528848+0 records in

14528848+0 records out

7438770176 bytes (7.4 GB, 6.9 GiB) copied, 29.7913 s, 250 MB/s

root@0182e6b37bd5:/# dd if=/dev/zero of=bigfile bs=1M count=100

100+0 records in

100+0 records out

104857600 bytes (105 MB, 100 MiB) copied, 0.0230156 s, 4.6 GB/s

root@0182e6b37bd5:/# dd if=/dev/zero of=bigfile bs=1M count=100 oflag=direct

100+0 records in

100+0 records out

104857600 bytes (105 MB, 100 MiB) copied, 3.35443 s, 31.3 MB/s

Docker默认隔离性

[root@docker-nodde1 ~]# free -m 系统内存使用情况

total used free shared buff/cache available

Mem: 1742 730 775 202 591 1012

Swap: 2063 3 2060

[root@docker-nodde1 ~]# docker run --rm --memory 200M -it ubuntu

root@6912bdc7b661:/# free -m

total used free shared buff/cache available

Mem: 1742 727 776 202 592 1014

Swap: 2063 2 2061

解决Docker的默认隔离性

[root@docker-nodde1 ~]# rpm -qa | grep lxc

lxc-libs-4.0.12-1.el9.x86_64

lxc-templates-4.0.12-1.el9.x86_64

lxcfs-5.0.4-1.el9.x86_64

运行lxcfs并解决容器隔离性

[root@docker-nodde1 ~]# lxcfs /var/lib/lxcfs &

[root@docker-nodde1 ~]# docker run -it -m 256m \

> -v /var/lib/lxcfs/proc/cpuinfo:/proc/cpuinfo:rw \

> -v /var/lib/lxcfs/proc/diskstats:/proc/diskstats:rw \

> -v /var/lib/lxcfs/proc/meminfo:/proc/meminfo:rw \

> -v /var/lib/lxcfs/proc/stat:/proc/stat:rw \

> -v /var/lib/lxcfs/proc/swaps:/proc/swaps:rw \

> -v /var/lib/lxcfs/proc/uptime:/proc/uptime:rw \

> ubuntu

容器特权

[root@docker-nodde1 ~]# docker run --rm -it busybox

这是因为容器使用的很多资源都是和系统真实主机公用的,如果允许容器修改这些重要资源,系统的稳 定性会变的非常差

#限制容器对网络有root权限

[root@docker-nodde1 ~]# docker run --rm -it --cap-add NET_ADMIN busybox

Docker Compose

[root@docker-nodde1 test]# vim bwmis.yml

services:

web:

image: nginx

ports:

  • "80:80"

db:

image: mysql:5.7

environment:

MYSQOL_ROOT_PASSWORD: lee

[root@docker-nodde1 ~]# docker compose -f test/bwmis.yml up -d

[+] Running 3/3

✔ Network test_default Created 0.1s

✔ Container test-web-1 Started 0.4s

✔ Container test-db-1 Started 0.4s

[root@docker-nodde1 ~]# docker compose -f test/bwmis.yml down

[+] Running 3/3

✔ Container test-web-1 Removed 0.1s

✔ Container test-db-1 Removed 0.0s

✔ Network test_default Removed

docker-compose start : 启动已经存在的服务,但不会创建新的服务

docker-compose stop : 停止正在运行的服务

docker-compose restart : 重启服务。

[root@docker-nodde1 test]# docker compose -f bwmis.yml ps

[root@docker-nodde1 test]# docker compose -f bwmis.yml logs web

构建和重新构建服务

[root@docker-nodde1 test]# cat Dockerfile

FROM busybox:latest

RUN touch /leefile

[root@docker-nodde1 test]# cat lee.Dockerfile

FROM busybox:latest

RUN touch /leefile2

[root@docker-nodde1 test]# vim test.yml

services:

test1:

image: test1

build:

context: /root/test/

dockerfile: lee.Dockerfile

command: ["/bin/sh","-c","sleep 3000"]

restart: always

container_name: busybox1

test2:

image: test2

build:

context: /root/test/

dockerfile: Dockerfile

command: ["/bin/sh","-c","sleep 3000"]

restart: always

container_name: busybox2

[root@docker-nodde1 test]# docker compose -f test.yml build

[root@docker-nodde1 test]# docker compose -f test.yml build test1 #指定文件中的服务

[root@docker test]# docker compose -f test.yml up --build 会先构建镜像后启动容器

[root@docker-nodde1 test]# docker compose -f test.yml pull

[root@docker-nodde1 test]# docker compose -f test.yml exec test1 sh

/ # #在正在运行的服务容器中执行命令

docker compose -f test.yml pull

docker compose -f test.yml config -q #加上q不显示详细信息

Docker Compose 的yml文件

镜像(image):

[root@docker-nodde1 test]# vim test.yml

services:

web:

image: nginx

mysql:

image: mysql:5.7

[root@docker-nodde1 test]# docker compose -f test.yml up -d

端口映射(ports):

[root@docker-nodde1 test]# vim test.yml

services:

web:

image: nginx

container_name: game

restart: always

expose:

  • 1234

ports:

  • "80:8080"

mysql:

image: mysql:5.7

[root@docker-nodde1 test]# docker compose -f test.yml up -d

services:

web:

image: nginx

container_name: game

restart: always

expose:

  • 1234

ports:

  • "80:8080"

mysql:

image: mysql:5.7

environment:

MYSQL_ROOT_PASSWORD: lee

[root@docker-nodde1 test]# docker compose -f test.yml up -d
存储卷(volumes):

services:

web:

image: nginx

container_name: game

restart: always

expose:

  • 1234

ports:

  • "80:8080"

mysql:

image: mysql:5.7

environment:

MYSQL_ROOT_PASSWORD: lee

test:

image: busybox

command: ["/bin/sh","-c","sleep 10000"]

restart: always

container_name: busybox3

volumes:

  • /etc/passwd:/tmp/passwd:ro

[root@docker-nodde1 test]# docker inspect busybox3

网络(networks)

services:

web:

image: nginx

container_name: webserver

network_mode: bridge 使用本机自带bridge网络

命令(command): 覆盖容器启动时默认执行的命令。例如

services:

test:

image: busybox

container_name: webserver22

command: ["/bin/sh","-c","sleep 100000"]

networks:

  • mynet1

  • mynet2

networks:

mynet1:

driver: bridge

mynet2:

driver: bridge

[root@docker-nodde1 test]# docker compose -f test.yml up -d

自定义网络(networks)

services:

test:

image: busybox

command: ["/bin/sh","-c","sleep 100000"]

restart: always

network_mode: default

container_name: busybox

test1:

image: busybox

command: ["/bin/sh","-c","sleep 100000"]

restart: always

networks:

  • mynet1

container_name: busybox1

test3:

image: busybox

command: ["/bin/sh","-c","sleep 100000"]

restart: always

networks:

  • mynet2

container_name: busybox2

networks:

mynet1:

driver: bridge

default:

external: true

name: bridge

mynet2:

ipam:

driver: default

config:

  • subnet: 172.25.0.0/16

gateway: 172.25.0.254

定义 Docker Compose 应用程序中使用的存储卷

services:

test:

image: busybox

command: ["/bin/sh","-c","sleep 3000"]

restart: always

container_name: busybox1

volumes:

  • data:/test

  • /etc/passwd:/tmp/passwd:ro

volumes:

data:

name: bwmis

案例

[root@docker-nodde1 ~]# dnf install haproxy -y --downloadonly --downloaddir=/mnt

[root@docker-nodde1 ~]# cd /mnt

[root@docker-nodde1 mnt]# rpm2cpio haproxy-2.4.22-3.el9_3.x86_64.rpm | cpio -id

[root@docker-nodde1 mnt]# cd etc/

[root@docker-nodde1 haproxy]# cp haproxy.cfg /var/lib/docker/volumes/conf/

[root@docker-nodde1 test]# vim test.yml

services:

web1:

image: nginx:latest

container_name: webserver1

restart: always

expose:

  • 80

volumes:

  • data_web1:/usr/share/nginx/html

networks:

  • internel

web2:

image: nginx:latest

container_name: webserver2

restart: always

expose:

  • 80

volumes:

  • data_web2:/usr/share/nginx/html

networks:

  • internel

haproxy:

image: haproxy:2.3

restart: always

container_name: haproxy

ports:

  • "80:80"

volumes:

  • /var/lib/docker/volumes/conf/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg

networks:

  • internel

  • extrnal

networks:

internel:

driver: bridge

extrnal:

driver: bridge

volumes:

data_web1:

name: data_web1

data_web2:

name: data_web2

[root@docker-nodde1 test]# echo webserver1 > /var/lib/docker/volumes/data_web1/_data/index.html

[root@docker-nodde1 test]# echo webserver2 > /var/lib/docker/volumes/data_web2/_data/index.html

[root@docker-nodde1 test]# curl 172.25.250.100

webserver1

[root@docker-nodde1 test]# curl 172.25.250.100

webserver2

相关推荐
向宇it9 分钟前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎
小蜗牛慢慢爬行11 分钟前
Hibernate、JPA、Spring DATA JPA、Hibernate 代理和架构
java·架构·hibernate
saynaihe1 小时前
安全地使用 Docker 和 Systemctl 部署 Kafka 的综合指南
运维·安全·docker·容器·kafka
星河梦瑾1 小时前
SpringBoot相关漏洞学习资料
java·经验分享·spring boot·安全
黄名富1 小时前
Redis 附加功能(二)— 自动过期、流水线与事务及Lua脚本
java·数据库·redis·lua
love静思冥想1 小时前
JMeter 使用详解
java·jmeter
言、雲1 小时前
从tryLock()源码来出发,解析Redisson的重试机制和看门狗机制
java·开发语言·数据库
TT哇1 小时前
【数据结构练习题】链表与LinkedList
java·数据结构·链表
Yvemil72 小时前
《开启微服务之旅:Spring Boot 从入门到实践》(三)
java
Anna。。2 小时前
Java入门2-idea 第五章:IO流(java.io包中)
java·开发语言·intellij-idea