问题描述
我有 3 个简单的微服务(mysql、apirest、gui),我开始使用 docker-compose:
I have 3 simple microservices (mysql, apirest, gui) that I start using docker-compose:
version: '3.2'
services:
mysql:
image: mysql/mysql-server:5.6
container_name: mysql
restart: always
volumes:
- mysql:/var/lib/mysql/data
ports:
- "3306:3306"
networks:
- mynetwork
deploy:
mode: replicated
replicas: 1
environment:
- MYSQL_ROOT_PASSWORD=mypwd
- MYSQL_USER=myuser
- MYSQL_PASSWORD=myuserpwd
- MYSQL_DATABASE=my-db
apirest:
image: .....apirest:latest
container_name: apirest
restart: always
volumes:
- apirest:/apirest/tmp
ports:
- "30000:3000"
networks:
- mynetwork
deploy:
mode: replicated
replicas: 2
gui:
image: ......gui:latest
container_name: gui
restart: always
links:
- apirest
ports:
- "34200:4200"
networks:
- mynetwork
networks:
mynetwork:
volumes:
apirest:
mysql:
mysql 和 apirest 微服务可以毫无问题地通信(我可以使用 mysql 从 apirest 连接到我的数据库strong> 作为主机名.
The mysql and the apirest microservices can communicate without problem (I can connect to my database from apirest using mysql as hostname.
但是当我尝试使用 apirest 作为主机名执行 http 请求(角度)时,我在 gui 微服务中收到以下错误:
But I got the following error in the gui microservice as soon as I try to perform an http request (angular) using apirest as hostname:
无法加载资源:net::ERR_NAME_NOT_RESOLVED
从 gui 微服务我可以 ping apirest:
from the gui microservice I can ping the apirest:
docker exec -it gui ping apirest
--- apirest ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.069/0.203/0.338 ms
如果我使用公共服务器地址(http://serverip:30000/api/test) 执行 http 请求而不是 apirest 没有问题,http 请求成功.
If I use the public server address (http://serverip:30000/api/test) to perform the http request instead of apirest there is no problem, the http request succeed.
我做错了什么??
谢谢
推荐答案
AJAX 请求是浏览器请求而不是服务器端请求,并且您的浏览器不是 mynetwork 的一部分.进行ajax请求(客户端浏览器需要是公共域或映射带有服务节点端口的主机文件).您仍然需要在浏览器主机中映射主机文件或在 gui 代码中使用带有服务节点端口的完整 url.
AJAX request is the browser request not the server side request and your browser is not a part of mynetwork.To make ajax request (Client browser need to be public domains or map host file with service node port).You still need to map host file in your browser host machine or use full url with service node port in your gui code.
如果你想避免使用端口,在我使用 Nginx 的情况下,代理是暴露服务的最佳方式
if you want to avoid using port, proxying is the best way to expose service in my case I am using Nginx
GUI--- ajax req(browser to server req)----> PROXY(NGINX)---(server to server)--> apirest
GUI--- ajax req(browser to server req)----> PROXY(NGINX)---(server to server)--> apirest
这篇关于码头工人 ERR_NAME_NOT_RESOLVED http ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!