首页 > 解决方案 > Nginx 简单代理在 Docker 中不起作用

问题描述

我有一个后端和一个前端,它们在 Docker 的两个容器中运行,两者都可以从我的浏览器及其端口访问:

localhost:8081 # frontend
localhost:8082 # backend

现在,我想使用一个接收所有流量(端口 80)并重定向的 Nginx 服务器:

localhost -> to frontend
localhost/api -> to the backend

在尝试了nginx.conf文件中的几乎所有内容(没有任何效果)之后,我在一个 SO Question 中发现我必须修改的文件是:

/etc/nginx/sites-enabled/default

所以我尝试修改它,现在nginx运行了。对于运行,我的意思是至少在我访问时localhost,会显示 nginx 欢迎页面。但是,我仍然无法让我的 nginx 路由流量(代理方式,而不是重定向)。

现在我的docker-compose文件具有以下外观(nginx 的片段加上这两个服务):

  nginx:
    image: nginx:latest
    ports:
      - 80:80
    volumes:
      - ./Dockerfiles/nginx/default:/etc/nginx/sites-enabled/default
    links:
      - frontend
      - backend
    depends_on:
      - frontend
      - backend
  frontend:
    build: ./Dockerfiles/frontend
    volumes:
      - ./Dockerfiles/frontend/www/src:/usr/src/app
      - ./logs/frontend/httpd:/var/logs/httpd
    ports:
      - "8081:3000"
    links:
      - backend
  backend:
    build: ./Dockerfiles/backend
    volumes:
      - ./Dockerfiles/backend/www:/var/www/html
      - ./logs/backend/httpd:/var/logs/httpd
    ports:
      - "8082:80"
    links:
      - "database"
      - "redis"
    depends_on:
      - database
      - redis

default如前所述,我的文件对于 nginx 配置是:

server {
        listen 80 default_server;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.php index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;
            proxy_pass http://frontend:8081/;
            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;
        }

        location /api {
            proxy_pass http://backend:8082/public/;
            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;
        }

}

例如,当我尝试访问我的/apiurl 时,nginx 告诉我的错误是:

nginx_1 | 2018/12/17 21:44:09 [错误] 6#6: *1 open() "/usr/share/nginx/html/api" 失败(2:没有这样的文件或目录),客户端:172.20.0.1 ,服务器:本地主机,请求:“GET /api HTTP/1.1”,主机:“本地主机”

似乎它正在尝试从本地文件系统中检索文件(鉴于 conf. 文件,我无法理解)。

任何线索,想法或提示?

标签: dockernginxdocker-composenginx-reverse-proxy

解决方案


将您的服务器配置放入:/etc/nginx/conf.d/default.conf,而不是启用站点。

文档:https ://hub.docker.com/_/nginx/

此外,您稍后将面临不同的问题。更改http://frontend:8081/;http://frontend:3000/;。因为 nginx 是直接联系前端容器,而不是整个主机。


推荐阅读