Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docker Nginx 容器直接访问宿主机 #8

Open
zhangyu921 opened this issue Nov 23, 2018 · 5 comments
Open

Docker Nginx 容器直接访问宿主机 #8

zhangyu921 opened this issue Nov 23, 2018 · 5 comments
Labels

Comments

@zhangyu921
Copy link
Owner

zhangyu921 commented Nov 23, 2018

在使用 nginx docker 容器配置反向代理的时候,默认不能直接使用 localhost,因为访问它指向的是这个容器本身。而本机的内网 ip 时常改变,如果没有联网还会没有内网地址,开发测试非常的不方便。

在 Desktop 环境下,可以使用 host.docker.internal docker 提供的特殊 DNS 访问宿主机。

如果是 Linux 环境还可以使用 docker 提供的 host networking,将容器的端口直接发布到宿主机上。

host networking 方法只能用于Linux环境下的docker,不支持 Docker Desktop for Mac,Docker Desktop for Windows,或 Docker EE for Windows Server。

举个例子:如果 Dockerfile EXPOSE的端口是 80,那么使用host networking方式 启动容器,就可以直接用宿主机的ip通过80端口访问这个服务,不需要指定 --port。同时容器也可以直接访问宿主机其他端口的服务,不需要通过内网ip。

方法很简单,命令启动时,加上--network host就可以了:

$ docker run --rm --network host nginx:alpine

在 docker-compose.yml 中使用:

version: '2'
services:
  nginx:
    image: nginx:alpine
    network_mode: "host"
    volumes:
      - './html:/usr/share/nginx/html'
      - './conf:/etc/nginx'
    restart: always

ref:

@mystterio
Copy link

https://docs.docker.com/network/host/ 官网的host network介绍中有这么一句“The host networking driver only works on Linux hosts, and is not supported on Docker Desktop for Mac, Docker Desktop for Windows, or Docker EE for Windows Server.”,所以windows下面不能用,,

@zhangyu921
Copy link
Owner Author

https://docs.docker.com/network/host/ 官网的host network介绍中有这么一句“The host networking driver only works on Linux hosts, and is not supported on Docker Desktop for Mac, Docker Desktop for Windows, or Docker EE for Windows Server.”,所以windows下面不能用,,

@mystterio 是的,感谢补充~

@maskwang
Copy link

maskwang commented Jul 28, 2019

mark

@suncunhu
Copy link

这个--network host只支持linux
那在 mac 下如何实现 容器内的nginx 反向代理宿主机的服务呢?

@zhangyu921
Copy link
Owner Author

@suncunhu 18.03版本后,可以使用host.docker.internal访问宿主机

@zhangyu921 zhangyu921 changed the title Docker Nginx 容器直接访问宿主机内网 Docker Nginx 容器直接访问宿主机 Dec 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants