我为 API 和前端使用不同的 Docker 容器。
frontend:
image: <my_frontend_image>
ports:
- "3000:3000"
api:
restart: always
build: ./<my_api_folder>
ports:
- "9002:9002"
在 API 方面,我有发送电子邮件的端点:
/emails/custom
在前端,我尝试向此端点发送请求:
$.ajax({
url: "http://api:9002/api/emails/custom",
dataType: "json",
type: "POST"
...
但这不起作用。看起来它再次向前端容器发送请求。
这里有什么问题吗?
更新:
也许这个问题也与我的 nginx 配置有关:
location / {
# Define the location of the proxy server to send the request to
# Web it's a name of docker container with frontend.
proxy_pass http://frontend:3000;
# Redefine the header fields that NGINX sends to the upstream server
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Define the maximum file size on file uploads
client_max_body_size 5M;
}
# Setup communication with API container.
location /api {
rewrite "^/api/(.*)$" /$1 break;
proxy_pass http://api:9002;
proxy_redirect off;
proxy_set_header Host $host;
}
您正在尝试从浏览器外部访问 api 服务,而不是从前端容器内访问 api 主机名。端口转发是由 docker 完成的,因此在外部您需要访问主机。例如。:http://localhost:9002
(例如,如果您使用 docker for mac)
可以找到类似的问题/答案here https://stackoverflow.com/questions/48845838/docker-connect-nodejs-container-with-apache-container/48846801#48846801
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)