运行 Consul on Vagrant:从来宾到主机的端口转发在 Mac OS X 上不起作用

Running Consul on Vagrant: Port forwarding from guest to host not working on Mac OS X

我想使用 Vagrant 在我的本地机器 (Mac OS X) 上设置一个带有 UI 的 Consul 集群。 到目前为止,我只是按照官方领事文档的入门说明进行操作:https://www.consul.io/intro/getting-started/join.html

为了能够从主机访问UI,我只是将这一行添加到提供的 Vagrantfile (https://github.com/hashicorp/consul/blob/master/demo/vagrant-cluster/Vagrantfile)

n1.vm.network "forwarded_port", guest: 8500, host: 8500

为了在来宾机器上使用 UI 启动 Consul,我通过 ssh 进入机器,然后简单地将 -ui 标志添加到提供的命令中:

consul agent -server -bootstrap-expect=1 \
    -data-dir=/tmp/consul -node=agent-one -bind=172.20.20.10 \
    -enable-script-checks=true -config-dir=/etc/consul.d -ui

Consul 启动没有问题,我可以从客户机执行:

curl -v 'http://localhost:8500/ui/'

并返回预期的 HTML 页面。

尝试在浏览器中或通过主机上的 curl 访问 http://localhost:8500/ui/ 是行不通的。在主机上使用 curl 结果:

*   Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 8500 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8500 (#0)
> GET /ui/ HTTP/1.1
> Host: localhost:8500
> User-Agent: curl/7.54.0
> Accept: */*
> 
* Empty reply from server
* Connection #0 to host localhost left intact
curl: (52) Empty reply from server

我在正确设置端口转发时遗漏了什么吗? 运行 vagrant up 之后的日志我觉得不错:

n1: Forwarding ports...
    n1: 8500 (guest) => 8500 (host) (adapter 1)

您有 2 个选择:

  1. 使用静态 IP(public network or private network),这样您就可以将您的 consul agent 绑定到静态 IP(例如 172.20.20.10),您将能够通过 http://172.20.20.10:8500/ui/ 进行访问从您的网络浏览器

注意:在这种情况下,您不需要在 Vagrantfile 中包含转发端口

  1. consul doc on bind option

The address that should be bound to for internal cluster communications. This is an IP address that should be reachable by all other nodes in the cluster. By default, this is "0.0.0.0", meaning Consul will bind to all addresses on the local machine

这样您就可以从您的主机

访问您虚拟机上的领事运行

注意:我的偏好是选项 #1

consul agent -server -bootstrap-expect=1 -data-dir=/tmp/consul -node=agent-one -bind=172.20.20.10 -client=172.20.20.10 -enable-script-checks=true -config-dir=/etc/consul.d -ui 是一个很好的解决方案,但它有副作用,任何 consul cli 操作都会 return 错误,因为它在 http 请求中使用 127.0.0.1。所以也许将 -client=172.20.20.10 更改为 -client=0.0.0.0 会更好。