NginxProxyManager / nginx-proxy-manager

Docker container for managing Nginx proxy hosts with a simple, powerful interface
https://nginxproxymanager.com
MIT License
22.17k stars 2.55k forks source link

nginx-proxy-manager + nextcloud:fpm = 502 Bad Gateway #928

Open talesam opened 3 years ago

talesam commented 3 years ago

I'm using two separate docker-compose files, some with npm and one with nextcloud. I get the npm network to use in the nextcloud, but I have an error when accessing the 502 Bad Gateway nextcloud.

Below my nextcloud docker-compose

version: '3.9'

services:
  nextcloud_db:
    image: postgres:13
    container_name: nextcloud_db
    restart: always
    volumes:
      - ./volumes/db:/var/lib/postgresql/data
    env_file:
      - db.env

  nextcloud:
    image: nextcloud:fpm
    container_name: nextcloud
    restart: always
    expose:
      - '80'
      - '9000'
    volumes:
      - ./volumes/nextcloud:/var/www/html
    environment:
      - POSTGRES_HOST=nextcloud_db
    env_file:
      - db.env
    depends_on:
      - nextcloud_db

networks:
  default:
    external:
      name: nginxproxymanager_default

My conteiners Captura de tela de 2021-03-06 20-17-25

Configuration SSL Captura de tela de 2021-03-06 20-11-29 Captura de tela de 2021-03-06 20-11-40

Captura de tela de 2021-03-06 20-25-01

sgb999 commented 3 years ago

i posted the same issue, there is a communication error somewhere between the database and the app, no idea how to fix, must be a bug in the program

talesam commented 3 years ago

Let's see if anyone finds an answer, I put it well specified.

If using the nextcloud: latest image works, but this image has apache built in, it doesn't make sense, it doesn't!

sgb999 commented 3 years ago

I think you're confused. It has nothing to do with the image that you are proxying to at all. Its an issue when the app talks to the database, it happens for any docker image you proxy to even if apache is not involved.

talesam commented 3 years ago

It's not a problem with the bank, it works for me if I change where nextlcoud is: fpm to nextcloud: latest, everything will work fine, but I don't want to use this image, as it comes with built-in apache.

Again, if I use the "nextcloud" image other than with ngnix, it works perfectly.

You can test this compose docker that will work:

version: '3.9'

services:
  nextcloud_db:
    image: postgres:13
    container_name: nextcloud_db
    restart: always
    volumes:
      - ./volumes/db:/var/lib/postgresql/data
    env_file:
      - db.env

  nextcloud:
    image: nextcloud:latest
    container_name: nextcloud
    restart: always
    volumes:
      - ./volumes/nextcloud:/var/www/html
    environment:
      - POSTGRES_HOST=nextcloud_db
    env_file:
      - db.env
    depends_on:
      - nextcloud_db

networks:
  default:
    external:
      name: nginxproxymanager_default

db.env

POSTGRES_PASSWORD=YOU_PASS
POSTGRES_DB=nextcloud
POSTGRES_USER=nextcloud
l4rm4nd commented 3 years ago

Sometimes the HTTP/2 support can break some stuff. Try disabling it, might help .. might not.

talesam commented 3 years ago

Às vezes, o suporte HTTP / 2 pode quebrar algumas coisas. Tente desativá-lo, pode ajudar ... talvez não.

That's not it, I had already tested it.

talesam commented 3 years ago

Nobody knows if it is possible to run the nextcloud:fpm image with nginx proxy manager?

It should work, since there is a web server running at npm, right?

How would it be to run npm with this docker-compose? (https://hub.docker.com/_/nextcloud)

version: '2'

volumes:
  nextcloud:
  db:

services:
  db:
    image: mariadb
    restart: always
    command: --transaction-isolation=READ-COMMITTED --binlog-format=ROW
    volumes:
      - db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=
      - MYSQL_PASSWORD=
      - MYSQL_DATABASE=nextcloud
      - MYSQL_USER=nextcloud

  app:
    image: nextcloud:fpm
    restart: always
    links:
      - db
    volumes:
      - nextcloud:/var/www/html
    environment:
      - MYSQL_PASSWORD=
      - MYSQL_DATABASE=nextcloud
      - MYSQL_USER=nextcloud
      - MYSQL_HOST=db

  web:
    image: nginx
    restart: always
    ports:
      - 8080:80
    links:
      - app
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    volumes_from:
      - app
aventustudio commented 3 years ago

I was able to fix similar problems with a custom nextcloud config: https://docs.nextcloud.com/server/21/admin_manual/configuration_server/reverse_proxy_configuration.html# You'll find examples in config.sample.php.

config.php

<?php

$CONFIG = [
    'overwritehost' => 'cloud.mydomain.com',
    'overwriteprotocol' => 'http',
    'trusted_proxies' => '172.26.0.1', # replace with internal nginx pm ip
#    'forwarded_for_headers' => ['HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR'] # not sure about this one yet
]
?>

I also added this in proxy manager (Edit Proxy Host/Advanced):

location = /.well-known/carddav {
  return 301 $forward_scheme://$server/remote.php/dav;
}

location = /.well-known/caldav {
  return 301 $forward_scheme://$server/remote.php/dav;
}

Not sure if it is necessary, I haven't testet cal and carddav yet.

talesam commented 3 years ago

Não tenho certeza se é necessário, ainda não testei cal e carddav.

For version 21 it is, for version 20 it is not.

gil00pita commented 3 years ago

Go to Advanced and try to add this:

    # set max upload size
    client_max_body_size 512M;
    fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    gzip on;
    gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 256;
    gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
    gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

    # HTTP response headers borrowed from Nextcloud `.htaccess`
    add_header Referrer-Policy                      "no-referrer"   always;
    add_header X-Content-Type-Options               "nosniff"       always;
    add_header X-Download-Options                   "noopen"        always;
    add_header X-Frame-Options                      "SAMEORIGIN"    always;
    add_header X-Permitted-Cross-Domain-Policies    "none"          always;
    add_header X-Robots-Tag                         "none"          always;
    add_header X-XSS-Protection                     "1; mode=block" always;

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

    # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
    location = / {
        if ( $http_user_agent ~ ^DavClnt ) {
            return 302 /remote.php/webdav/$is_args$args;
        }
    }

    # Make a regex exception for `/.well-known` so that clients can still
    # access it despite the existence of the regex rule
    # `location ~ /(\.|autotest|...)` which would otherwise handle requests
    # for `/.well-known`.
    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in `.htaccess` that concern `/.well-known`.

        location = /.well-known/carddav { return 301 /remote.php/dav/; }
        location = /.well-known/caldav  { return 301 /remote.php/dav/; }

        location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
        location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

        # Let Nextcloud's API for `/.well-known` URIs handle all other
        # requests by passing them to the front-end controller.
        return 301 /index.php$request_uri;
    }

On my machine works, and don't forget to add server IP and port not the IP of the container.

talesam commented 3 years ago

Can I take a look at your docker-compose?

huangwb8 commented 2 years ago

@gil00pita I use your config and got a 502 Bad Gateway. May I just have a look at your docker-compose.yml?

Hadatko commented 1 year ago

Hello guys, just quickly i can describe how i managed nextcloud-fpm working. It took me more time for such tiny change. The biggest issue was that i didn't realized that my npm saw nextcloud folder as /var/www/nextcloud and nextcloud saw its folder in /var/www/html/nextcloud.

Settings are relly easy: volume for nextcloud container:

Explanation image bellow -> Port is random free number diferent to nginx default. Just choose it here. I added hostname to nginx called nginx, but you can use nginx ip.
image

Generate certificates image Now save to get certificates generated (if you have your own you can skip this step). If not you need backed up ssl_certificate and ssl_certificate_key lines in your config which is afaik hidden in gui. You can attach in container for nginx and go /data/nginx/proxy_host/ and here choose correct config (In config you will find your url from first image) and copy somewhere these two values.

Into advanced tab you need copy everything from official nextcloud webpage (https://docs.nextcloud.com/server/latest/admin_manual/installation/nginx.html) what is inside brackets (only inside) server {} for ssl (443 port) without server {} (this adavanced data are saved inside server{}). image Modifications in advance tab: root -> in my case unmodified as nginx see nextcloud in /var/www/nextcloud ssl_certificate and ssl_certificate_key with you certificates (for example if you backed lines up based on steps above) fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; -> as nextcloud container store nextcloud/* in /var/www/html add_header Cache-Control "public, max-age=15778463"; -> Didn't know how to correctly replace asset_immutable (i just made it working and writing these lines) so i removed it. fastcgi_pass nextcloud2:9000; -> You can see i am not calling handler but directly server:port. In my case nextcloud container hostname is nextcloud2, but you can use ip:port. I think that is all. Do not forget have nginx and nextcloud on same network. In that case you don't need expose nextcloud ports. Or expose ports and then you can use system ip. (i think container ip can be changed on reboot, so i am using hostname rather and not exposing ports)

 # Path to the root of your installation
    root /var/www/nextcloud/;

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/
  ssl_certificate /etc/letsencrypt/live/npm-30/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/npm-30/privkey.pem;

    # Prevent nginx HTTP Server Detection
    server_tokens off;

    # HSTS settings
    # WARNING: Only add the preload option once you read about
    # the consequences in https://hstspreload.org/. This option
    # will add the domain to a hardcoded list that is shipped
    # in all major browsers and getting removed from this list
    # could take several months.
    #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;

    # set max upload size and increase upload timeout:
    client_max_body_size 512M;
    client_body_timeout 300s;
    fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    gzip on;
    gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 256;
    gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
    gzip_types application/atom+xml text/javascript application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/wasm application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

    # Pagespeed is not supported by Nextcloud, so if your server is built
    # with the `ngx_pagespeed` module, uncomment this line to disable it.
    #pagespeed off;

    # The settings allows you to optimize the HTTP2 bandwitdth.
    # See https://blog.cloudflare.com/delivering-http-2-upload-speed-improvements/
    # for tunning hints
    client_body_buffer_size 512k;

    # HTTP response headers borrowed from Nextcloud `.htaccess`
    add_header Referrer-Policy                   "no-referrer"       always;
    add_header X-Content-Type-Options            "nosniff"           always;
    add_header X-Download-Options                "noopen"            always;
    add_header X-Frame-Options                   "SAMEORIGIN"        always;
    add_header X-Permitted-Cross-Domain-Policies "none"              always;
    add_header X-Robots-Tag                      "noindex, nofollow" always;
    add_header X-XSS-Protection                  "1; mode=block"     always;

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

    # Add .mjs as a file extension for javascript
    # Either include it in the default mime.types list
    # or include you can include that list explicitly and add the file extension
    # only for Nextcloud like below:
    include mime.types;
    types {
        text/javascript js mjs;
    }

    # Specify how to handle directories -- specifying `/index.php$request_uri`
    # here as the fallback means that Nginx always exhibits the desired behaviour
    # when a client requests a path that corresponds to a directory that exists
    # on the server. In particular, if that directory contains an index.php file,
    # that file is correctly served; if it doesn't, then the request is passed to
    # the front-end controller. This consistent behaviour means that we don't need
    # to specify custom rules for certain paths (e.g. images and other assets,
    # `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
    # `try_files $uri $uri/ /index.php$request_uri`
    # always provides the desired behaviour.
    index index.php index.html /index.php$request_uri;

    # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
    location = / {
        if ( $http_user_agent ~ ^DavClnt ) {
            return 302 /remote.php/webdav/$is_args$args;
        }
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Make a regex exception for `/.well-known` so that clients can still
    # access it despite the existence of the regex rule
    # `location ~ /(\.|autotest|...)` which would otherwise handle requests
    # for `/.well-known`.
    location ^~ /.well-known {
        # The rules in this block are an adaptation of the rules
        # in `.htaccess` that concern `/.well-known`.

        location = /.well-known/carddav { return 301 /remote.php/dav/; }
        location = /.well-known/caldav  { return 301 /remote.php/dav/; }

        location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
        location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

        # Let Nextcloud's API for `/.well-known` URIs handle all other
        # requests by passing them to the front-end controller.
        return 301 /index.php$request_uri;
    }

    # Rules borrowed from `.htaccess` to hide certain paths from clients
    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

    # Ensure this block, which passes PHP files to the PHP process, is above the blocks
    # which handle static assets (as seen below). If this block is not declared first,
    # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
    # to the URI, resulting in a HTTP 500 error response.
    location ~ \.php(?:$|/) {
        # Required for legacy support
        rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;

        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        set $path_info $fastcgi_path_info;

        try_files $fastcgi_script_name =404;

        include fastcgi_params;
        #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;

        fastcgi_param PATH_INFO $path_info;
        fastcgi_param HTTPS on;

        fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
        fastcgi_param front_controller_active true;     # Enable pretty urls
        fastcgi_pass nextcloud2:9000;

        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;

        fastcgi_max_temp_file_size 0;
    }

    # Serve static files
    location ~ \.(?:css|js|mjs|svg|gif|png|jpg|ico|wasm|tflite|map)$ {
        try_files $uri /index.php$request_uri;
        add_header Cache-Control "public, max-age=15778463";
        access_log off;     # Optional: Don't log access to assets

        location ~ \.wasm$ {
            default_type application/wasm;
        }
    }

    location ~ \.woff2?$ {
        try_files $uri /index.php$request_uri;
        expires 7d;         # Cache-Control policy borrowed from `.htaccess`
        access_log off;     # Optional: Don't log access to assets
    }

    # Rule borrowed from `.htaccess`
    location /remote {
        return 301 /remote.php$request_uri;
    }

    location / {
        try_files $uri $uri/ /index.php$request_uri;
    }

Troubleshooting: Red dot means wrong config. Sometimes i could edit and save. Sometimes i had to restart nginx after changes (e.g. modifying nginx configuration as described above in container directly. These changes are not permanent and you will not see them in gui. So once you will do some changes and you are ok with them you need save them using gui). Always read logs from both nginx and nextcloud container. image To get rid of red dot i suggest comment code untill it will pass and then uncomment and figure out which line is causing error and fix (syntax/logix/semantic). If you will have error during saving, you need edit file manually and restart nginx.

172.19.0.5 - 18/Aug/2023:21:21:14 +0000 "GET /index.php" 200 -> likely wrong set of SCRIPT_FILENAME Error 404 when accesing on web -> could be wrong set of root

github-actions[bot] commented 6 months ago

Issue is now considered stale. If you want to keep it open, please comment :+1: