容器网络入门操作2
https://hub.docker.com/_/nginx

测试2:

拉取一个nginx镜像文件,这里使用的是最小化的版本
docker pull nginx:alpine
然后启动nginx容器:
1
docker run --name nginx1 -d --net bridge nginx:alpine
Copied!
然后通过docker inspect查看nginx1这个容器的ip地址:
1
[email protected]:/data/mysql3# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nginx1
2
172.17.0.3
Copied!
在宿主机上使用 curl 172.17.0.3 即可访问nginx容器的主页:
1
[email protected]:/data/mysql3# curl 172.17.0.3
2
<!DOCTYPE html>
3
<html>
4
<head>
5
<title>Welcome to nginx!</title>
6
<style>
7
body {
8
width: 35em;
9
margin: 0 auto;
10
font-family: Tahoma, Verdana, Arial, sans-serif;
11
}
12
</style>
13
</head>
14
<body>
15
<h1>Welcome to nginx!</h1>
16
<p>If you see this page, the nginx web server is successfully installed and
17
working. Further configuration is required.</p>
18
19
<p>For online documentation and support please refer to
20
<a href="http://nginx.org/">nginx.org</a>.<br/>
21
Commercial support is available at
22
<a href="http://nginx.com/">nginx.com</a>.</p>
23
24
<p><em>Thank you for using nginx.</em></p>
25
</body>
26
</html>
Copied!
但是这个nginx在宿主机以外是无法访问的,关于docker内置支持的四种网络类型,可以参考这张图:
docker内置支持的四种网络类型
所以,要实现跨宿主机的网络访问,首先要把容器的端口暴露在宿主机的网络接口上,原理与路由器上的NAT类似。通过增加参数 -p [宿主端口]:[容器端口] 实现,例如:
1
docker run --name nginx2 -d --net bridge -p 10080:80 nginx:alpine
Copied!
docker ps现在可以看到端口转发的情况:
1
[email protected]:~# docker ps -a
2
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3
925878944cd8 nginx:alpine "nginx -g 'daemon of…" 4 seconds ago Up 3 seconds 0.0.0.0:10080->80/tcp nginx2
4
9f2bd3b88b8e nginx:alpine "nginx -g 'daemon of…" 54 minutes ago Up 54 minutes 80/tcp nginx1
5
5104ca874b9e mysql:5.7 "docker-entrypoint.s…" 2 hours ago Up 2 hours 3306/tcp, 33060/tcp mysql4
Copied!
也可以使用docker port查看:
1
[email protected]:~# docker port nginx2
2
80/tcp -> 0.0.0.0:10080
Copied!
使用iptables -t nat -vnL可以看到对应的NAT规则:
1
[email protected]:~# iptables -t nat -vnL
2
Chain PREROUTING (policy ACCEPT 1 packets, 169 bytes)
3
pkts bytes target prot opt in out source destination
4
7 1201 DOCKER all -- * * 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL
5
6
Chain INPUT (policy ACCEPT 1 packets, 169 bytes)
7
pkts bytes target prot opt in out source destination
8
9
Chain OUTPUT (policy ACCEPT 2 packets, 146 bytes)
10
pkts bytes target prot opt in out source destination
11
0 0 DOCKER all -- * * 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL
12
13
Chain POSTROUTING (policy ACCEPT 2 packets, 146 bytes)
14
pkts bytes target prot opt in out source destination
15
0 0 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0
16
0 0 MASQUERADE tcp -- * * 172.17.0.4 172.17.0.4 tcp dpt:80
17
18
Chain DOCKER (2 references)
19
pkts bytes target prot opt in out source destination
20
0 0 RETURN all -- docker0 * 0.0.0.0/0 0.0.0.0/0
21
0 0 DNAT tcp -- !docker0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:10080 to:172.17.0.4:80
Copied!
这样,通过其他主机,访问这台宿主机的http://ip:10080端口,就能访问到nginx2容器内的80端口,获取nginx主页信息。
Last modified 1yr ago
Copy link