Linked docker-compose containers making http requests

*爱你&永不变心* 提交于 2019-12-31 05:03:25

问题


I've been looking on the web for a while and haven't found a solution to my problem which is similar to this StackOverflow question Docker HTTP-requests between containers. But this answer is already what I'm doing in my computer. I'm providing my docker-compose file

version: "3"
services:
  web:
    image: ecdavis15/tsn-web-server
    ports:
      - "3000:3000"
    links:
      - app
  app:
    image: ecdavis15/tsn-app-server
    ports:
      - "3030:3030"
    links:
      - mongo
  mongo:
    image: mongo
    ports:
      - "27017:27017"
    volumes:
      - ./data/db:/data/db

In my web container I make an http get request to http://app:3030/history or maybe http://app:3030/rules but I'm not seeing the request find its way to the app container. What I'm seeing in the browser console is this error message net::ERR_NAME_NOT_RESOLVED. I'm not sure why the http request isn't getting into the app container since it's linked to the web container. Any ideas?


回答1:


Since you make an Ajax call it will be sent by the browser which is client side and not server side. So when you make a call from <IP>:3000 to app:3030 for API, your browser has no idea what app is. So you have few things you can do

Using host file

/etc/hosts

<IP> app 

Then when you browse app using app:3000, app:3030 will automatically point to the correct address.

Using javascript to determine API url

You can use javascript to get the url that you should be using for api

document.location.scheme + "://" + document.location.hostname + ":3030"

Using nginx

You can create nginx reverse proxy

location / {
   proxy_pass http://localhost:3000;

   location /api {
      proxy_pass http://localhost:3030;
   }
}

This will require some change in your code file so that you use /api



来源:https://stackoverflow.com/questions/46987726/linked-docker-compose-containers-making-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!