3
respostas

502 Bad Gateway em Servidor LEMP

Olá estou com um servidor LEMP Linux Oracle 8, Nginx, MySql, PHP.

Que está apresentando: **502 Bad Gateway **

/etc/nginx/nginx.conf

#user  nobody;
worker_processes  4;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    gzip_types text/plain text/xml text/css
               text/comma-separated-values
               text/javascript application/x-javascript
               application/atom+xml;
    log_format specialLog '$remote_addr forwarded for $http_x_real_ip - $remote_user [$time_local]  '
                          '"$request" $status $body_bytes_sent '
                          '"$http_referer" "$http_user_agent"';

        access_log /var/log/nginx/access.log specialLog;
        sendfile        on;
        keepalive_timeout  65s;
        server_tokens off; #Oculta versao Nginx
        gzip  on;

        client_max_body_size                    30M;
        client_body_timeout                     1m;
        client_header_timeout                   1m;
        send_timeout                            1m;

        server {
                listen                          80 ;
                server_name                     teste;
                index           index.html
                return 301 https://$host$request_uri;
        
                }
        server {
                listen                          443 ssl default_server;
                server_name                     teste;
                root                            /var/www/html;
                ssl_certificate                 cert/certificate.pem;
                ssl_certificate_key             cert/privatekey.pem;
                ssl_session_timeout             5m;
                ssl_protocols                   SSLv2 SSLv3 TLSv1.2;
                ssl_ciphers                     ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
                ssl_prefer_server_ciphers       on;
                client_max_body_size 64M;
                client_body_buffer_size 64M;
                error_page 404 /var/www/html/wp-content/themes/hello-theme-child/404.php;

                location /404.php{
                        internal;
                }

                location ~* /(?:uploads|files)/.*\.php$ {
                        deny all;
                }

                location ~ \.css {
                        add_header  Content-Type    text/css;
                }
                location ~ \.js {
                        add_header  Content-Type    text/javascript;
                }

                location / {
                        index index.php index.html index.htm;
                        try_files $uri $uri/ /index.php?$args;
                }


                location ~* \.(ico|gif|jpg|jpe?g|png|css|js)$ {
                        expires max;
                }

                location ~ ^(.+?\.php)(/.*)?$ {
                        try_files $uri =404;
                        fastcgi_split_path_info ^(.+\.php)(/.+)$;
                        fastcgi_index                   index.php;
                        fastcgi_read_timeout            60;
                        fastcgi_pass 127.0.0.1:9000;
                        fastcgi_param   PATH_INFO       $fastcgi_path_info;
                        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                        include fastcgi_params;
                        proxy_set_header        Host            $host;
                        proxy_cache_valid       200 24h;
                        proxy_cache_use_stale   error timeout invalid_header updating http_500 http_502 http_503 http_504;

                }
               location ~ \.php$ {
                        try_files $uri =404;
                        fastcgi_split_path_info ^(.+\.php)(/.+)$;
                        fastcgi_index index.php;
                        fastcgi_read_timeout 60;
                        fastcgi_pass 127.0.0.1:9000;
                        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                        include fastcgi_params;
                        proxy_cache_valid       200 24h;
                        proxy_cache_use_stale   error timeout invalid_header updating http_500 http_502 http_503 http_504;
                }
        }

}
3 respostas

/etc/nginx/default.d/php.conf

# pass the PHP scripts to FastCGI server
#
# See conf.d/php-fpm.conf for socket configuration
#
index index.php index.html index.htm;

location ~ \.(php|phar)(/.*)?$ {
    fastcgi_split_path_info ^(.+\.(?:php|phar))(/.*)$;

    fastcgi_intercept_errors on;
    fastcgi_index  index.php;
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_param  PATH_INFO $fastcgi_path_info;
    fastcgi_pass   php-fpm;
}

/etc/php.ini

[PHP]
security.limit_extensions = .php
allow_url_fopen = on
safe_mode=off
engine = On
short_open_tag = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = -1
disable_functions =
disable_classes =
zend.enable_gc = On
zend.exception_ignore_args = On
expose_php = Off
max_execution_time = 30
max_input_time = 60
memory_limit = 512M
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
doc_root =
user_dir =
enable_dl = Off
file_uploads = On
; upload_max_filesize = 2M // 05-10-22
upload_max_filesize = 4M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
cli_server.color = On
date.timezone =America/Rio_Branco
pcre.jit=0
pdo_mysql.default_socket=
sendmail_path = /usr/sbin/sendmail -t -i
mail.add_x_header = Off
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
bcmath.scale = 0
session.save_handler = files
session.use_strict_mode = 0
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.cookie_samesite =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.sid_length = 26
session.trans_sid_tags = "a=href,area=href,frame=src,form="
session.sid_bits_per_character = 5
zend.assertions = -1
tidy.clean_output = Off
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
ldap.max_links = -1

/etc/php-fpm.d/www.conf

[www]
user = apache
group = apache
listen = 127.0.0.1:9000
listen.acl_users = apache,nginx
listen.allowed_clients = 127.0.0.1
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
slowlog = /var/log/php-fpm/www-slow.log
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path]    = /var/lib/php/session
php_value[soap.wsdl_cache_dir]  = /var/lib/php/wsdlcache
;php_value[opcache.file_cache]  = /var/lib/php/opcache

sudo systemctl status nginx

Nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
  Drop-In: /usr/lib/systemd/system/nginx.service.d
           └─php-fpm.conf
   Active: active (running) since Tue 2024-02-27 17:58:58 -05; 16h ago
  Process: 15821 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
  Process: 15820 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 15817 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 15823 (nginx)
    Tasks: 5 (limit: 12292)
   Memory: 5.0M
   CGroup: /system.slice/nginx.service
           ├─15823 nginx: master process /usr/sbin/nginx
           ├─15824 nginx: worker process
           ├─15825 nginx: worker process
           ├─15826 nginx: worker process
           └─15827 nginx: worker process

Feb 27 17:58:58 g2tic-dev systemd[1]: Stopped The nginx HTTP and reverse proxy server.
Feb 27 17:58:58 g2tic-dev systemd[1]: Starting The nginx HTTP and reverse proxy server...
Feb 27 17:58:58 g2tic-dev nginx[15820]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Feb 27 17:58:58 g2tic-dev nginx[15820]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Feb 27 17:58:58 g2tic-dev systemd[1]: Started The nginx HTTP and reverse proxy server.

sudo systemctl status php-fpm

php-fpm.service - The PHP FastCGI Process Manager
   Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2024-02-27 17:58:58 -05; 17h ago
 Main PID: 15818 (php-fpm)
   Status: "Processes active: 0, idle: 5, Requests: 0, slow: 0, Traffic: 0req/sec"
    Tasks: 6 (limit: 12292)
   Memory: 24.0M
   CGroup: /system.slice/php-fpm.service
           ├─15818 php-fpm: master process (/etc/php-fpm.conf)
           ├─15829 php-fpm: pool www
           ├─15830 php-fpm: pool www
           ├─15831 php-fpm: pool www
           ├─15832 php-fpm: pool www
           └─15833 php-fpm: pool www

Feb 27 17:58:58 g2tic-dev systemd[1]: Starting The PHP FastCGI Process Manager...
Feb 27 17:58:58 g2tic-dev systemd[1]: Started The PHP FastCGI Process Manager.

index.php

<?php
    phpinfo();
?>

Alguém consegui me auxiliar?

Oii, Robson, tudo bem?

O erro 502 Bad Gateway no seu servidor LEMP aparece porque o servidor da web (o Nginx para o seu caso) não conseguiu receber uma resposta válida de um servidor upstream, que seria o PHP-FPM.

O PHP-FPM precisa estar em execução. Você pode fazer isso com o seguinte comando no terminal:

systemctl status php-fpm

Se o PHP-FPM não estiver em execução, você pode iniciar com o seguinte comando:

systemctl start php-fpm

Se o PHP-FPM estiver em execução, o problema pode estar na configuração do Nginx. No seu arquivo de configuração, você tem duas localizações para arquivos .php, o que pode estar causando o problema. Olha só:

location ~ ^(.+?\.php)(/.*)?$ {
    resto do código
}

location ~ \.php$ {
    resto do código
}

Ambos os blocos estão tentando lidar com arquivos .php, o que pode estar causando uma confusão para o Nginx. Recomendo que você mantenha apenas um deles. Por exemplo, você pode manter o segundo bloco e remover o primeiro:

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_index index.php;
    fastcgi_read_timeout 60;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    proxy_cache_valid       200 24h;
    proxy_cache_use_stale   error timeout invalid_header updating http_500 http_502 http_503 http_504;
}

Depois disso, por favor, tente reiniciar o Nginx para que as alterações sejam efetuadas:

systemctl restart nginx

Se outra dúvida surgir, estamos disponíveis.

Abraços!

Caso este post tenha lhe ajudado, por favor, marcar como solucionado ✓.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software