React app (in a docker container) cannot access API (in a docker container) on AWS EC2

痞子三分冷 提交于 2020-08-05 10:10:12

问题


my question in a nutshell... Within the context of AWS EC2 hosting, what do I need to do to allow my frontend container to fetch from an endpoint on my backend container, locally?

Details:

I have 2 Docker containers running via docker-compose. Locally, they work fine and I am able to query the backend container (which is a node app) from my frontend container (a React app) using:

http://localhost:3000/someendpoint

After moving everything onto an AWC EC2 instance I am no longer able to connect to localhost in this manner. Nothing has changed in my files.

Here is part of my docker-compose.yml that contains the 2 services in question:

backend:
    container_name: somename-backend
    image: somename-backend
    environment:
      NODE_ENV: production
    volumes:
      - ./server:/server
    ports:
      - "3000:3000"

  frontend:
    container_name: somename-frontend
    image: somename-frontend
    environment:
      NODE_ENV: production
    volumes:
      - ../src:/src
    ports:
      - "8081:8081"
    depends_on:
      - backend

If I have the frontend query:

http://ec2-12-345-67-890.us-west-2.compute.amazonaws.com:3000/someendpoint

I get the result I expect. However, this is an "external" url query and I think it would be better to make that query internal. I have tried:

http://localhost:3000/someendpoint //fails

and

http://0.0.0.0:3000/someendpoint //fails

and

http://ec2-12-345-67-890.us-west-2.compute.amazonaws.com:3000/someendpoint //succeeds

Do I need to expose something in my security group that I might be missing?

I exposed the various ports to my IP address and again, using the full public domain everything works but I do not think I should have to use the full public domain in order for my react frontend to fetch from a url in my backend when both docker containers are hosted on the same EC2 instance and running via docker-compose.


回答1:


Your react app runs on your browser & hence localhost will point back to your local laptop's IP address and not the EC2 instance's IP. Using the external URL is the right way to go as your app users will also have to access the backend from external sources.



来源:https://stackoverflow.com/questions/50139880/react-app-in-a-docker-container-cannot-access-api-in-a-docker-container-on-a

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