首页 > 解决方案 > 如何使用 cURL 从自身连接到 PHP 容器?

问题描述

当我尝试使用 连接到容器本身curl -v localhost时,我得到:

*   Trying 127.0.0.1:80...
* TCP_NODELAY set
* connect to 127.0.0.1 port 80 failed: Connection refused
*   Trying ::1:80...
* TCP_NODELAY set
* Immediate connect fail for ::1: Address not available
*   Trying ::1:80...
* TCP_NODELAY set
* Immediate connect fail for ::1: Address not available
* Failed to connect to localhost port 80: Connection refused
* Closing connection 0
curl: (7) Failed to connect to localhost port 80: Connection refused

我提到我既不想从容器连接到主机,也不想从主机连接到容器(我只能找到关于这两个用例的信息),而是从容器内部连接到容器本身

这是我的 docker-compose.yml

services:
  php:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    ports:
      - '8000:80'
    volumes:
      - ./app:/var/www/html

以防万一,我提到我正在使用图像php:7.3-fpm-alpine

我还用curl -v php(使用容器的名称)进行了测试,我得到了:

*   Trying 172.18.0.5:80...
* TCP_NODELAY set
* connect to 172.18.0.5 port 80 failed: Connection refused
* Failed to connect to content_php port 80: Connection refused
* Closing connection 0
curl: (7) Failed to connect to content_php port 80: Connection refused

虽然ping php可以:

PING php (172.18.0.5): 56 data bytes
64 bytes from 172.18.0.5: seq=0 ttl=64 time=0.262 ms

我还通过添加docker-compose.ymlEXPOSE: 80进行了测试,得到了相同的结果。 我也用 8000 端口进行了测试,我得到了相同的结果。
curl localhost:8000

我注意到docker ps在 9000 上设置了一个默认端口:

PORTS  
9000/tcp, 0.0.0.0:8000->80/tcp  

当我执行curl localhost:9000并得到:

curl: (56) Recv failure: Connection reset by peer

为了能够从自身连接到容器,我缺少什么?

标签: phpdockercurldocker-compose

解决方案


从自身访问容器时应该可以使用localhost,如下图所示:

Dockerfile:

FROM httpd:2.4
RUN apt-get update && apt-get install curl

接着:

$ docker build -t temp .
$ docker run --detach --name temp temp
$ docker exec temp curl localhost
<html><body><h1>It works!</h1></body></html>

使用尽可能少的设置对您的图像进行尝试,以查明问题。此外,请验证您的图像是否可以从外部访问。如果它可以从您的主机访问,并且无法从容器内使用 访问localhost,那么它的服务器配置bindlisten地址可能会限制它。将其设置为0.0.0.0或相当于说“任何”。


推荐阅读