Issue
My front-end in running on port 3000 and my back-end on port 8000. I've deployed my app using EC2 instance and I've installed Nginx and PM2. When I try to open the app on the browser using my public DNS address the app appears for a short period of time then it breaks. It shows me the error
net::ERR_CONNECTION_REFUSED
GET http://localhost:8000/api/info/countByType net::ERR_CONNECTION_REFUSED
Here is where my front-end is making the request
export const countByCity = createAsyncThunk("info/countByCity", async() => {
try{
const res = await axios.get("http://localhost:8000/api/info/countByCity");
return res.data;
}catch(error){
console.log(error.response)
}
});
and here is my /etc/nginx/sites-available/default file configuration
server {
listen 80;
listen [::]:80;
root /usr/share/nginx/booking.com;
index index.html index.htm index.nginx-debian.html;
server_name _;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri /index.html;
}
location /api {
proxy_pass http://ec2-54-167-89-197.compute-1.amazonaws.com:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
I have changed the proxy_pass to be my Public IP address. The previous configuration was http://localhost:8000.
My question is : My front end is trying to reach the localhost:8000 endpoint. Should I change it to be my Public DNS address instead? Example : http://ec2-54-167-89-197.compute-1.amazonaws.com/api/info/countByCity ?
Solution
This code in your front end is running in the user's web browser, not on the EC2 server:
const res = await axios.get("http://localhost:8000/api/info/countByCity");
When that code tries to access localhost
it is trying to access a server running on your local laptop/PC, not a server in AWS. You need to change that localhost
address to be the public IP of your EC2 server.
This proxy configuration on your Nginx server:
proxy_pass http://ec2-54-167-89-197.compute-1.amazonaws.com:8000;
Is going all the way out to the Internet and back, just to access a service that is running on a different port of the same server. You need to change that to be localhost
for both security and efficiency.
Answered By - Mark B Answer Checked By - Mildred Charles (WPSolving Admin)