You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EC2部署前后端应用Nginx配置疑问:前端请求localhost:8000报错,是否需替换为公网DNS地址?

解决EC2上前后端应用通过Nginx代理时的连接拒绝问题

你的问题核心很明确:浏览器里的localhost指的是用户自己的本地机器,而不是你的EC2服务器。前端代码里写死http://localhost:8000/api/...,当用户在自己电脑上打开你的公网地址时,浏览器会尝试连接自己本地的8000端口——但这个端口根本没跑你的后端服务,所以必然抛出ERR_CONNECTION_REFUSED。

下面给你两种最靠谱的解决方案,按优先级排序:

方案1:使用相对路径(最优推荐)

直接把前端请求地址改成相对路径,这样会自动复用当前页面的域名和端口,然后通过Nginx的代理规则转发到后端。

修改你的前端请求代码:

export const countByCity = createAsyncThunk("info/countByCity", async() => {
  try{
    // 去掉域名,只用相对路径
    const res = await axios.get("/api/info/countByCity");
    return res.data;
  }catch(error){
    console.log(error.response)
  }
});

同时,建议把你的Nginx配置里的proxy_pass改回http://localhost:8000——因为你的后端服务是直接跑在EC2实例本地的,用localhost转发更高效,还能避免公网IP变动带来的问题:

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 {
    // 改回localhost,因为后端在EC2本地运行
    proxy_pass http://localhost: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;
  }
}

修改完成后,重启Nginx让配置生效:

sudo systemctl restart nginx

方案2:硬编码公网地址(不推荐,仅作备选)

如果你一定要用绝对路径,那就把前端请求里的localhost:8000替换成你的EC2公网DNS或IP,但注意要去掉端口(因为Nginx已经监听80端口,会帮你转发到后端的8000):

export const countByCity = createAsyncThunk("info/countByCity", async() => {
  try{
    const res = await axios.get("http://ec2-54-167-89-197.compute-1.amazonaws.com/api/info/countByCity");
    return res.data;
  }catch(error){
    console.log(error.response)
  }
});

这种方式的缺点很明显:如果你的EC2公网IP/DNS变动,你得重新修改前端代码并重新部署,维护成本很高,所以优先选方案1。

最后再确认两个关键点:

  • 后端服务确实通过PM2正常运行在8000端口,可以用pm2 list查看状态
  • EC2的安全组已经开放了80端口(你能打开前端页面说明已经开了),后端的8000端口不需要开放公网访问——因为Nginx是在EC2内部转发请求,安全组只需要允许80端口的入站流量即可。

内容的提问来源于stack exchange,提问作者Amauri Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:17:38