php - 如何使用 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
为了能够从自身连接到容器,我缺少什么?
解决方案
从自身访问容器时应该可以使用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
,那么它的服务器配置bind
或listen
地址可能会限制它。将其设置为0.0.0.0
或相当于说“任何”。
推荐阅读
- jasper-reports - Jasper Report Chart 操作 labelExpression
- javascript - 使用百分比进行 css 转换以动画 dom 转换的替代方法
- python - 如何正确比较ctime?
- c++ - UART流打包;流还是向量?
- java - Spring Boot Gateway 过滤阻塞请求
- ms-access - 微软PPT中添加牛津逗号的快捷方法?
- python - 使用 grid() 函数的“AttributeError”
- angular - 角度 5 的 SCSS 格式化程序
- firebase - Firebase 身份验证:scrypt 密码哈希参数是什么意思?
- php - 使用模态作为模板来编辑/删除