今天像往常一样准备利用Docker启动一个Web应用docker run -d -p 80:80 --name nginx nginx
,结果发现无法访问,docker ps
看了一下,容器已经启动了,日志也正常。
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c0e3ec43f5d3 nginx "nginx -g 'daemon of…" 5 seconds ago Up 4 seconds 0.0.0.0:80->80/tcp nginx
看一下端口监听也没问题
$ lsof -i:80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 6443 root 4u IPv6 75314 0t0 TCP *:http (LISTEN)
docker logs nginx
查看日志也没有异常,但是在容器内是可以访问服务的
$ docker exec -it nginx bash
root@c0e3ec43f5d3:/# curl -I localhost
HTTP/1.1 200 OK
Server: nginx/1.17.10
Date: Fri, 22 May 2020 07:00:01 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 14 Apr 2020 14:19:26 GMT
Connection: keep-alive
ETag: "5e95c66e-264"
Accept-Ranges: bytes
但是在主机下却无法访问
$ curl -I localhost
curl: (56) Recv failure: Connection reset by peer
首先想到的是防火墙,因为用的是CentOS7,于是用systemctl status firewalld
看一下防火墙状态
$ systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
好奇怪!
后来突然想到有可能是容器网络的问题,于是在启动容器时指定网络--net=host
$ docker run -d -p 80:80 --name nginx --net=host nginx
WARNING: Published ports are discarded when using host network mode
7f16107986aa8dedbcfe3d6ca9b4b9a42758392ead9c45f2d686479260d2c741
使用host网络启动之后,会打印一行警告
WARNING: Published ports are c when using host network mode
意思是使用主机网络可能会跟宿主机有冲突造成已发布的端口会失效,但目前已经可以访问容器网络了
$ curl -I localhost
HTTP/1.1 200 OK
Server: nginx/1.17.10
Date: Fri, 22 May 2020 07:08:26 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 14 Apr 2020 14:19:26 GMT
Connection: keep-alive
ETag: "5e95c66e-264"
Accept-Ranges: bytes
在拿浏览器访问,可以看到熟悉的Welcome to nginx!
页面了。