问题描述
我正在尝试从我们的应用 ping 我们的一个 Rails 微服务(处理电子邮件),但出现标题错误。
我们的微服务在 localhost:3101
上的 docker 中运行,而我们的应用也在 docker 上的 localhost:3000 上运行 - 我已经用邮递员请求 ping 了它,并且运行良好。
我已经在我们的 ENV 变量中设置了我们的身份验证令牌和电子邮件服务 API,如下所示:-
EMAIL_SERVICE=http://localhost:3101
EMAIL_SERVICE_TOKEN=1234
这是我的 EmailService
:-
class EmailService
require 'net/http'
HEADER = { 'Content-Type': 'application/json' }.freeze
ENDPOINTS = {
root: ENV['EMAIL_SERVICE'],test_email: {
post: {
url: '/api/test_email'
}
}
}
def initialize
@token = ENV['EMAIL_SERVICE_TOKEN']
end
def call_api(section,action,data,method='POST')
address_url = ENDPOINTS[section][action][:url]
uri = URI.parse("#{ENDPOINTS[:root]}#{address_url}")
# Create the HTTP objects
http = Net::HTTP.new(uri.host,uri.port)
if method == 'POST'
request = Net::HTTP::Post.new(
uri.request_uri,HEADER
)
request.body = data.merge({ auth_token: @token }).to_json
else
request = Net::HTTP::Get.new(
uri.request_uri,HEADER
)
end
http.use_ssl = true
response = http.request(request)
end
end
知道我错过了什么吗?
解决方法
我假设这两个微服务都运行在不同的 docker 容器上。
我认为问题在于,当 docker 从容器外部收到您的请求,然后尝试向 localhost
发出 HTTP 请求时,它实际上是在向其自己的 localhost
发出请求(因此在容器)而不是您机器的 localhost
。要解决此问题,与其尝试向 localhost
发送请求,不如让 docker 内的应用将请求发送到 host.docker.internal:DESIRED_PORT
,这会告诉 docker 使用其主机的 localhost
。
您可以在此处阅读更多相关信息:
https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds