docker端口映射无法访问的解决
程序员文章站
2022-06-04 19:47:19
...
表现
- systemctl status docker,显示正常,可以pull,push,build
- 宿主机访问外网没问题,可以连上ubuntu的阿里的源
- 运行容器映射的端口在本机无法访问,用curl 127.0.0.1:端口,显示:
curl: (56) Recv failure: Connection reset by peer
- docker build的时候,使用apt-get install xx,无法访问,哪怕镜像源是国内的阿里之类的.
在改为 docker build --network host后又可以了
原因:
docker的网桥出问题了,导致映射端口无效,docker run -d -p 8080:80, 非常确定容器内的应用正常启动,curl 127.0.0.1:8080失败
验证问题:
用于验证的镜像
-
也可以直接下载已经写好的镜像: simple_server,直接验证
-
用golang编写一个简单的http服务,编译为simple_server
package main import ( "flag" "fmt" "net/http" ) func indexHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello world") } func main() { var port int flag.IntVar(&port, "p", 8080, "端口号,默认为8080") flag.Parse() fmt.Println("监控在端口", port) http.HandleFunc("/", indexHandler) err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil) if err != nil { fmt.Println("错误: ", err) } }
-
编写Dockerfile
FROM ubuntu RUN echo 'deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse \n\ deb-src http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse \n\ deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse \n\ deb-src http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse \n\ deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse \n\ deb-src http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse \n\ deb http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse \n\ deb-src http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse \n\ deb http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse \n\ deb-src http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse '>/etc/apt/sources.list RUN apt-get update -y RUN apt-get install curl -y COPY simple_server /home/ CMD ["/home/simple_server", "-p", "80"]
-
放在同一个目录,并执行:
docker build . --network host -t simple_server
, 目录:[[email protected] tmp]# tree server server ├── Dockerfile └── simple_server 0 directories, 2 files
运行容器进行验证
- 运行:docker run -d -p 8080:80 simple_server
- 进入容器运行:
curl 127.0.0.1
, 成功打印:hello world
- 在宿主机上运行:
curl 127.0.0.1:8080
, 一直卡住,然后报no route 之类的错误