nginx как обратный прокси для экспресс-сервера 504 Тайм-аут шлюза

Я новичок в nginx и NodeJS. Я пытаюсь настроить свой сервер nginx на машине Fedora 26 в качестве обратного прокси-сервера для экспресс-сервера на порту 3000. Я следил за каждым шагом, но по какой-то причине у меня возникает ошибка тайм-аута шлюза 504.

Это мой файл /etc/nginx/nginx.conf:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

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

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
            try_files $uri /index.html;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers PROFILE=SYSTEM;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

Как видите, я создал папку с доступными сайтами, а затем установил ссылку на сайты с поддержкой, которые включены.

Внутри доступных сайтов у меня есть файл с этим:

# the IP(s) on which your node server is running. I chose port 3000.
upstream musiciansdb {
    server 127.0.0.1:3000;
    keepalive 8;
}

# the nginx server instance
server {
    listen 0.0.0.0:80;
    server_name musiciansdb.com musiciansdb;
    access_log /var/log/nginx/musiciansdb.log;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
            proxy_pass http://musiciansdb.com/;
        proxy_redirect off;

    }

}

Статус nginx:

● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-11-03 11:19:17 UTC; 2s ago
  Process: 937 ExecReload=/bin/kill -s HUP $MAINPID (code=exited, status=0/SUCCESS)
  Process: 981 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
  Process: 980 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 979 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 982 (nginx)
    Tasks: 2 (limit: 4915)
   CGroup: /system.slice/nginx.service
           ├─982 nginx: master process /usr/sbin/nginx
           └─983 nginx: worker process

Nov 03 11:19:17 myserver.localdomain systemd[1]: Starting The nginx HTTP and reverse proxy server...
Nov 03 11:19:17 myserver.localdomain nginx[980]: nginx: [warn] could not build optimal types_hash, you should increase either types_hash_max_size: 2048 or types_hasNov 03 11:19:17 myserver.localdomain nginx[980]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Nov 03 11:19:17 myserver.localdomain nginx[980]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Nov 03 11:19:17 myserver.localdomain nginx[981]: nginx: [warn] could not build optimal types_hash, you should increase either types_hash_max_size: 2048 or types_hasNov 03 11:19:17 myserver.localdomain systemd[1]: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument
Nov 03 11:19:17 myserver.localdomain systemd[1]: Started The nginx HTTP and reverse proxy server.

netstat -lntp | grep 3000

tcp6 0 0 :::3000 :::* LISTEN 3524/node

curl http://127.0.0.1:3000/ отвечает HTML-кодом моего приложения

Я уже отключил SElinux.

Я перезапускал сервер nginx после каждой настройки, даже перезапускал машину. Если я перейду прямо к порту 3000, веб-приложение будет там.

Что мне не хватает?

Спасибо


person Gonzalo Castillo    schedule 03.11.2017    source источник
comment
Оба сервера работают на одном хосте? (Никаких виртуальных машин, докер-контейнеров и т. Д.?)   -  person JoshWillik    schedule 04.11.2017
comment
В своем вопросе вы упомянули, что создали .conf файл в папке sites-available, но ваша конфигурация nginx показывает, что вы включаете все из sites-enabled. Это ошибка?   -  person JoshWillik    schedule 04.11.2017
comment
@JoshWillik Оба сервера работают на одном хосте. Я создал .conf файл внутри sites-available, затем сделал ссылку (ln -s) на него внутри sites-enabled   -  person Gonzalo Castillo    schedule 04.11.2017


Ответы (1)


Кажется, это плохая линия.

proxy_pass http://musiciansdb.com/;

Когда вы создаете восходящий бэкэнд в nginx, вы должны будете называть его тем же именем позже.

У вас есть:

upstream musiciansdb {
server 127.0.0.1:3000;
keepalive 8;
}

Вам нужно проксировать этот сервер с помощью этой строки (без .com):

proxy_pass http://musiciansdb;

В противном случае вы пытаетесь получить доступ к musiciansdb.com (извне, через порт 80, как это сделал бы браузер клиента).

Также обратите внимание, что serverfault.com - лучший сайт для вопросов системного администрирования.

person edgars    schedule 03.11.2017
comment
Привет! вот и все. Я поменял его на proxy_pass http://musiciansdb; и теперь он работает. Большое тебе спасибо. - person Gonzalo Castillo; 04.11.2017