docker run -d --name web nginx
nginx 默认的端口是 80 端口,此时我们是没有办法访问的。
好的,通过前面的学习我们已经知道,这个 web 容器四连接到 bridge
网桥上的,那我们查看一下。
docker network inspect bridge
"Containers": {
"d6abced642ad8e2be7d7bbb880a8a3bd08414735e3c1151379ac60572e672239": {
"Name": "web",
"EndpointID": "d84522fac6bb4da13b18b9ecc965a803bfdf37b82da4be774d8c490e04b61411",
"MacAddress": "02:42:ac:11:00:03",
"IPv4Address": "172.17.0.3/16",
"IPv6Address": ""
},
"da991beadf34ef53be9cf3de8f0c5ba1599b76f4433f6627f96c46c09751ecf5": {
"Name": "test1",
"EndpointID": "252a63d6f44927222cdbb2fa761d6cd24120d19a995893b549ccff73803d3a05",
"MacAddress": "02:42:ac:11:00:02",
"IPv4Address": "172.17.0.2/16",
"IPv6Address": ""
}
},
我们可以看到 web 容器确实是连接到 bridge
上的,而且ip地址是 172.17.0.3,那我们再尝试ping一下这个ip地址。
[vagrant@10 ~]$ ping 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.163 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.047 ms
是可以ping通的,那 80 端口是否能访问呢?
[vagrant@10 ~]$ telnet 172.17.0.3 80
Trying 172.17.0.3...
Connected to 172.17.0.3.
Escape character is '^]'
我们可以看到是能访问的,那么通过 curl 来访问 web 的nginx 服务界面。
[vagrant@10 ~]$ curl 172.17.0.3:80
Welcome to nginx!
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.
For online documentation and support please refer to
nginx.org.
Commercial support is available at
nginx.com.
Thank you for using nginx.
再测试通过本机的80端口看看是否能获取
[vagrant@10 ~]$ curl 127.0.0.1:80
curl: (7) Failed connect to 127.0.0.1:80; 拒绝连接
很显然是不行的。
我们刚刚通过访问容器的ip地址成功获取了 nginx运行的web的html界面。此时我们在本机是可以访问这个服务器的,但是其他设备呢?答案是不能的。
原因很简单,外界想访问我们这个容器的80端口,必须要知道 web 容器的 ip地址,但是这个ip地址是私有的,并不能在局域网内访问,只能在本机访问,那么是否可以通过 本机在局域网内的IP地址,例如 192.168.2.133,然后加上80端口访问呢,答案是不行的。
那如何解决?可以通过在外界访问 192.168.2.133:80 的时候转发到 172.17.0.3:80 即可。
这里我们需要用到 docker端口映射 功能。
b4f832fdcfc3c5ddeda380fbbad0be9ca5c64e51868aad17f8b75dc1d3dce263
[vagrant@10 ~]$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b4f832fdcfc3 nginx "nginx -g 'daemon of…" 5 seconds ago Up 4 seconds 0.0.0.0:80->80/tcp web
da991beadf34 busybox "/bin/sh -c 'while t…" 22 hours ago Up 20 minutes test1
-p 参数为设定端口映射
测试curl获取本地80端口是否能够获取web内容
[vagrant@10 ~]$ curl 127.0.0.1:80
Welcome to nginx!
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.
For online documentation and support please refer to
nginx.org.
Commercial support is available at
nginx.com.
Thank you for using nginx.
成功获取。
查看当前虚拟机的ip地址
$: ip a
3: eth1: mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:16:41:c1 brd ff:ff:ff:ff:ff:ff
inet 192.168.2.32/24 brd 192.168.2.255 scope global noprefixroute dynamic eth1
valid_lft 5411sec preferred_lft 5411sec
inet6 fe80::a00:27ff:fe16:41c1/64 scope link
valid_lft forever preferred_lft forever
然后在笔记本的浏览器中访问 http://192.168.2.32:80/
我们可以获取到 web 内容了。
这是因为当我们访问虚拟机的80端口时,设定的端口映射会帮我们转发到 web 容器的 80 端口上,这样我们才成功访问到容器内nginx的内容。