gpt4 book ai didi

docker - 如何使用同一网络中的localhost访问其他Docker容器中的一个容器的端口

转载 作者:行者123 更新时间:2023-12-02 19:59:05 24 4
gpt4 key购买 nike

我可以使用带有端口映射的localhost访问本地计算机中的docker容器端口,但无法以类似方式在其他容器中访问它。

我的docker-compose文件创建了具有80:80端口映射的Ubuntu和Nginx容器。当我尝试从Ubuntu访问Nginx URL时,端口拒绝连接。我可以使用容器名称访问端口,但不能使用localhost访问。

.
├── Dockerfile
└── docker-compose.yml

docker-compose.yml文件内容
version: '2'

services:
web:
image: nginx
ports:
- "80:80"
links:
- userver
depends_on:
- userver

userver:
build:
context: .
dockerfile: Dockerfile


Dockerfile内容
FROM ubuntu

RUN apt-get update && apt-get install -y net-tools curl
CMD tail -f /dev/null
docker-practice $ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c3f06dc519d8 nginx "nginx -g 'daemon of…" 4 hours ago Up 10 minutes 0.0.0.0:80->80/tcp docker-practice_web_1
40324fa76612 docker-practice_userver "/bin/sh -c 'tail -f…" 4 hours ago Up 10 minutes 80/tcp docker-practice_userver_1

使用本地主机从本地主机访问Nginx URL
docker-practice $ curl http://localhost -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 03:35:46 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

使用本地主机从Ubuntu容器访问Nginx URL
root@40324fa76612:/# curl http://localhost -I
curl: (7) Failed to connect to localhost port 80: Connection refused

使用容器名称从Ubuntu容器访问Nginx URL
root@40324fa76612:/# curl http://docker-practice_web_1 -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 03:42:13 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

我期望在具有localhost的Ubuntu docker容器中进行端口访问,但是该端口拒绝连接。

最佳答案

容器本身就像机器(计算机)一样工作。因此,如果您输入一个容器并调用“localhost”,则localhost指向该容器。容器的整体思想是“包含”其环境。尝试在使用容器时不再使用localhost。

使用容器名称或服务名称(在docker-compose网络中)。

关于docker - 如何使用同一网络中的localhost访问其他Docker容器中的一个容器的端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55584814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com