用nginx docker 做反向代理出现502 Bad Gateway

纵饮孤独 提交于 2019-12-04 07:55:07

用nginx docker 做反向代理出现502 Bad Gateway

主机上有个nodejs应用:http://127.0.0.1:8888,外网不能直接访问端口8888,只能访问80端口,想通过nginx做反向代理来访问nodejs应用 。
具体步骤如下:

启动nginx

  1. 使用docker启动nginx
sudo docker run --name=nginx \
 -p 80:80  \
 -v /home/dev/nginx/web/www:/usr/share/nginx/html \ 
 -v /home/dev/nginx/web/conf.d:/etc/nginx/conf.d \
 -d nginx
  1. 配置nginx
    编辑 /home/dev/nginx/web/conf.d/default.conf 配置如下:
server {
    listen 80;
    access_log /usr/share/nginx/html/mylog.log;
    error_log /usr/share/nginx/html/myerror.log;
    location / {
        proxy_redirect off;  
        proxy_set_header Host $host;  
        proxy_set_header X-Real-IP $remote_addr;  
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
        proxy_pass http://127.0.0.1:8888;    
      }
}

地址 http://127.0.0.1:8888 是 nodejs 编写的一个hello world实例,可以正常访问

  1. 重启nginx
 sudo docker exec -it nginx /etc/init.d/nginx reload
  1. 测试
$ curl 127.0.0.1:80
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.15.6</center>
</body>
</html>

出现了502错误,检查了半天的nginx配置,后来发现反向代理地址配置有问题:

 proxy_pass http://127.0.0.1:8888;    

因为nginx在docker中,所以不能使用127.0.0.1:8888来访问宿主机里的nodejs应用,docker内部实际上实现了一个虚拟网桥docker0,所以要通过宿主机内网地址(192.168.102.1)来访问.
将nginx配置改为:

server {
    listen 80;
    access_log /usr/share/nginx/html/mylog.log;
    error_log /usr/share/nginx/html/myerror.log;
    location / {
        proxy_redirect off;  
        proxy_set_header Host $host;  
        proxy_set_header X-Real-IP $remote_addr;  
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
        proxy_pass http://192.168.102.1:8888;    
      }
}

问题完美解决!

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