Dockerコンテナ内からホスト側ポートにアクセス
Dockerのネットワーク。
2022/11/05 時点
Docker Desktop for Mac/Windowsの場合
DNS名 host.docker.internal を使うと、コンテナ内からホストにアクセスできるIPが得られるので、これでホスト側の任意のポートにアクセスする
docker run --add-host ... または docker-composeのextra_hosts で任意の名前とIPの組合せを指定する
ホスト側のIPアドレスを知っておく必要がある
参考
Networking features in Docker Desktop for Mac | Docker Documentation
Networking features in Docker Desktop for Windows | Docker Documentation
Dockerのコンテナの中からホストOS上のプロセスと通信する方法 - Qiita
ネットワーク構築機能 — Docker-docs-ja 19.03 ドキュメント
Linuxの場合
Docker version 20.10.0 2020-12-08 リリース以降
code:shell
$ docker run -it --add-host=host.docker.internal:host-gateway image
root@7829011183a6:/# cat /etc/hosts
127.0.0.1 localhost
...
172.17.0.1 host.docker.internal
172.20.0.7 7829011183a6
code:compose.yml
services:
app:
extra_hosts:
- "host.docker.internal:host-gateway"
参考
Docker Engine release notes | Docker Documentation
Support host.docker.internal in dockerd on Linux moby/moby#40007
Docker Engine(Linux)でコンテナからホスト側のサービスにアクセスする(host.docker.internal) - CLOVER🍀
linuxでhost.docker.internalを使う - Qiita
Docker version 20.10.0 以前
host networkモードで起動し、コンテナにIPアドレスを割り当てずにホスト上のportを直接開く
docker run --network host ...
参考
Use host networking | Docker Documentation
ホスト・ネットワークの使用 — Docker-docs-ja 19.03 ドキュメント
docker compose でも可能
コンテナ間通信もhost経由で行うことになる
code:compose.yml
services:
app:
network_mode: "host"