docker 的 Nginx:反向代理不起作用

Nginx with docker: Reverse Proxy doesn't work

最近想设置一个反向代理服务器。我拉了一个 nginx docker 图像,我 运行 使用这个命令 docker 容器:

docker run -d --name ngtest -p 4080:80 nginx

然后我更新了 /etc/nginx/nginx.conf,如下所示:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server{
        listen 80;
        location /nexus/ {
            proxy_pass    http://192.168.0.30:8081/;
        }
    }
}

当我尝试打开页面时,容器在重新启动后工作 http://192.168.0.30:4080,我得到了默认的Nginx页面。

然而,当我尝试这个 url: http://192.168.0.30:4080/nexus 时,我得到了一个 404 错误页面。

从日志看,nginx 并没有将 url 转发到我在 nginx.conf 中设置的页面,而是尝试在本地目录中查找页面:

2020/03/11 16:10:34 [error] 6#6: *251 open() "/usr/share/nginx/html/nexus" failed (2: No such file or directory), client: 192.168.0.153, server: localhost, request: "GET /nexus HTTP/1.1", host: "192.168.0.30:4080"
192.168.0.153 - - [11/Mar/2020:16:10:34 +0000] "GET /nexus HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36" "-"

我的步骤有问题吗?

谢谢,

亚历克斯

问题是,即使您更新了配置,您仍然在做:

include /etc/nginx/conf.d/*.conf;

正在加载/etc/nginx/conf.d/default.conf如果未提供服务器名称,则根据确定服务器名称未找到时使用的服务器的规则,这将是默认服务器。

你应该这样做:

将您的服务器定义保存到配置文件:

server{
    listen 80;
    location /nexus/ {
        proxy_pass    http://192.168.0.30:8081/;
    }
}

然后运行

docker run -d -p 4080:80 -v (path_to_your_config):/etc/nginx/conf.d/default.conf nginx

这将用您的配置替换默认配置。然后,如果您需要进行更改,只需进行更改并重新启动容器即可。