簡體   English   中英

從特定端口上的 docker 容器到達主機

[英]Reach host machine from docker container on specific port

我正在使用網絡主機運行我的 docker 容器。 我可以在容器中使用ping localhost命令 ping 我的 localhost,一切都很好。 但我無法到達localhost:8000 有沒有辦法可以從 docker 容器到達特定端口上的本地主機?

這是我正在嘗試做的事情:

I have an API on my host machine that is runing on port 8000. When I try to curl from my docker container to that api, I can't. 這就是我將連接從橋接更改為主機的原因。

在我這樣做之后,我能夠 ping localhost(不確定哪個 localhost),但我假設它是主機。 Curl 向我返回此錯誤。

GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect to localhost port 8000: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html ) in file /var/www/vendor /guzzlehttp/guzzle/src/Handler/CurlFactory.php 在第 200 行

當我嘗試告訴net localhost 它也不起作用。 (無法解析主機或類似的東西)。 我以 root 身份從 docker 容器內部執行所有操作。

我的 docker 容器基於以下圖像php:7.2-apache構建

我將連接設置回橋接並使用了文檔中的host.docker.internal主機,但沒有成功。 我仍然可以從我的容器host.docker.internal ping 並得到響應

PING host.docker.internal (192.168.65.2) 56(84) 字節數據。 來自 192.168.65.2 (192.168.65.2) 的 64 個字節:icmp_seq=1 ttl=37 time=0.771 ms 來自 192.168.65.2 (192.168.65.2) 的 64 個字節:icmp_seq=2 ttl=37 time=1.20 ms 來自 192.168.65.2 的 64 個字節(192.168.65.2): icmp_seq=3 ttl=37 時間=0.548 毫秒

GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect to host.docker.internal port 8000: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html ) in file /var /www/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php 上線 200

I started my laravel api with php artisan serve using the following parameters php artisan serve --host=host.docker.internal --port=8000

我可以從我的瀏覽器訪問它

Laravel development server started on http://host.docker.internal:8000/ [Thu Jul 23 10:00:24 2020] 192.168.xx:60126 [200]: /favicon.ico

但是 docker 容器仍然無法從容器中訪問服務器。

最后,我嘗試使用 curl 訪問http://host.docker.internal並且工作正常。 問題出在港口。 可能是防火牆還是阻止它的東西? 我在具有 TCP 連接的公共、私有和域網絡的入站規則上列出了 Windows 中的 8000 端口,但這也不起作用。 我很困惑。

我關了防火牆還是沒有成功

問題解決了

When I was doing the curl request I was trying to reach a port in the following way: host.docker.internal:8000 - This was my curl URL leading to connectiong refused.

之后,我檢查 Guzzle 是否可以在不指定 url 的情況下以某種方式設置端口。

所以我在文檔中找到了這個 我用它來指定我的端口8000並使用以下命令運行我的工匠服務器

php artisan serve --host=host.docker.internal --port=8000

我也將我的APP_URL設置為APP_URL=http://host.docker.internal/

從那里開始,一切都像魅力一樣。

看這個問題How to access host port from docker container

如果您使用的是 linux 參數--net="host"將起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM