出现错误:宿主机不能访问 Docker 容器内部

问题引入

1、首先,我暴露了端口 8080 ,创建了映射也是 -p 8080:8080

2、容器内部执行 curl 127.0.0.1:8080/hello 是可以正常访问的

docker network create –driver bridge –subnet 172.03^C.1/16 –gateway 172.03.0.0 my_net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
taopanfeng/junit 0.1 09dd0295d9b9 32 seconds ago 684MB
taopanfeng/junit latest 09dd0295d9b9 32 seconds ago 684MB
<none> <none> 8e8dab3fa688 19 minutes ago 684MB
redis latest 74d107221092 37 hours ago 104MB
java 8 d23bdf5b1b1b 3 years ago 643MB

[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
[root@localhost ~]#
[root@localhost ~]# docker run --name a1 -p 8080:8080 -d taopanfeng/junit:0.1
ab16751218412bdd52eed596156415b045e07d55cd29ad5e3dcb08abb60151e5
[root@localhost ~]#
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ab1675121841 taopanfeng/junit:0.1 "java -jar /app/juni…" 3 seconds ago Up 3 seconds 0.0.0.0:8080->8080/tcp a1
[root@localhost ~]#
[root@localhost ~]# curl 127.0.0.1:8080/hello
curl: (56) Recv failure: Connection reset by peer #===> 本地不能访问
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# docker exec -it a1 curl 127.0.0.1:8080/hello
Hello World! #===> 容器内部是可以访问的
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
186a93879c74 bridge bridge local
46c6571d6d39 host host local
37fb6a796f7a none null local

原因分析

以下都是我的猜测而已。

1
2
3
可能是因为的克隆虚拟机导致的。
因为我的3号虚拟机,是根据 1号虚拟机克隆出来的。Docker 默认分配的网络是:172.17.0.1/16
1号和3号网络搞重复了,所以出问题了。使用 --net

在这里插入图片描述

解决方案

启动容器时,使用 –net host 来指定,使用 host 方式启动容器。

默认是 bridge,host 可以避免 ip 重复问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@localhost ~]# docker rm -f a1   #===> 删除原有容器
a1
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# docker run --name a1 -p 8080:8080 --net host -d taopanfeng/junit:0.1
WARNING: Published ports are discarded when using host network mode
316d635e009af0ac052f99849934d4a2874a23261ce620b67788d008143c5de6
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# curl 127.0.0.1:8080/hello
Hello World! #===>成功访问
[root@localhost ~]#
[root@localhost ~]# docker exec -it a1 curl 127.0.0.1:8080/hello
Hello World!
[root@localhost ~]#

在这里插入图片描述