無法從 Docker 容器存取 localhost

無法從 Docker 容器存取 localhost

我一步步遵循本教學:https://www.youtube.com/watch?v=NZGu-9KQVsE

  • 我建立了一個 Dockerfile :

來自 ubuntu: 傑米

RUN : \
    && apt-get update \
    && DEBIAN_FRONTEND=noninteractive apt-get install -y \
        curl \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*
  • 我建置了 docker 映像:
docker build -t mycurl .
  • 我使用運行圖像
docker run --add-host host.docker.internal:host-gateway --rm -ti mycurl bash
  • 我使用啟動了本地伺服器
python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
  • 但是當我嘗試從容器存取它時,出現逾時:
root@da4d8b1f4ae4:/# curl host.docker.internal:8000
curl: (28) Failed to connect to host.docker.internal port 8000 after 133451 ms: Connection timed out

我的 /etc/hosts 是:

root@da4d8b1f4ae4:/# cat /etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.1  host.docker.internal
172.17.0.2  da4d8b1f4ae4

知道為什麼嗎?我使用的是 Ubuntu 22.04.4 LTS

答案1

我透過執行以下命令解決了我的問題:

sudo ufw allow 8000

相關內容