Currently I have two container inside AWS EC2 instance.One of them is React app. It uses nginx. This app should send request to golang web service which is inside another container. They are both in same EC2 instance. When i open browser and go to EC2 instance’s public IP address i am able to see my React app is working. When i try to send request to golang web service it says that "(failed)net::ERR_CONNECTION_REFUSED". I am able to use curl request inside EC2 and receive response. How can i do the same on React Request.
Here is the my axios post
axios.post('http://localhost:9234/todos', { "name": todo, "completed": false },).then((res) => {
console.log(res)
if (res.data.todo.name === todo) {
setTodos([...todos, todo]);
}
}).catch((err) => { console.log(err) });
Here is my request with curl
curl -d '{"id":9,"name":"baeldung"}' -H 'Content-Type: application/json' http://localhost:9234/todos
2
Answers
from your details it seems likely that one or more of the following is true:
Furthermore,
localhost
as @Jaroslaw points out is from the persective of the browser. Thatlocalhost
should also be the IP of the ec2 instance or dns that resolves to that IP.To be clear, the react webapp doesn’t run on the ec2 instance. Its static assets such as DOM elements and Javascript get served to the browser and it runs there.
As @Daniel said javascript gets served to the browser and it runs there. So when your browser requesting the address
localhost
it actually means your computer’s localhost. To access the golang server you need to forward the9234
port from the docker container.And then also you need to open the
9234
port in firewall of your ec2 instance then you can access your go server using the public address of your ec2 from your browser.But this is not recommended to expose the ports to access your server. You may use nginx to listen on your port 80 and then load balance the requests to your go server. Here is a yaml you can add in your docker-compose to use nigx:
And the nginx conf should be: