503 ошибка nginx

Sometimes you may get 503 Service Temporarily Unavailable error in NGINX due to various reasons. In this article we will look at what is 503 service temporarily unavailable error, and how to fix 503 service temporarily unavailable error in NGINX.

503 Service Temporarily Unavailable Error means that NGINX is unable to handle the request as it is temporarily overloaded or facing resource constraints. It is different from 500 internal server error where the server is simply unable to process your request. In this case, the server continues to function properly but has chosen to return 503 error code.

Bonus Read : How to Fix 500 Internal Server Error in NGINX

How to Fix 503 Service Temporarily Unavailable Error in NGINX

Here is how to fix 503 service temporarily unavailable error in NGINX.

1. Reboot NGINX Server

One of the easiest ways to fix 503 service temporarily unavailable error is to simply restart NGINX server. Many times, NGINX may get overloaded due to too many open connections and temporary files. Restarting your server will close all these open connections and delete temporary files that are causing the bottleneck. If NGINX is a reverse proxy with multiple web servers, make sure to reboot even the web servers down the chain to ensure that your website/application is completely refreshed.

Bonus Read : How to Fix 504 Gatweway Timeout Error in NGINX

2. Check for Unexpected Updates / Maintenance

Have you enabled auto-updates in your web site/application? If so, then it might be downloading/installing updates for one or more plugins. This is quite common in CMS based systems like WordPress and Magento. In such cases, just turn off auto-updates in your system.

Similarly, check if you have any scheduled maintenance running in the background. In such cases also, your web server will return 503 service temporarily unavailable.

Bonus Read : How to Fix 502 Bad Gateway in NGINX

3. Server Connectivity

NGINX may also throw 503 service temporarily unavailable error if it is unable to connect to the web server (e.g Apache) or any of the third-party APIs.

Since today’s web architecture requires multiple web servers and third-party services, NGINX is likely to give 503 service temporarily unavailable if any of them goes down. In such cases check if all web servers and third party services are up and running.

Bonus Read : How to Increase Request Timeout in NGINX

4. Examine Server Logs

NGINX server log records the IP address, device, requested URL, response code and date time for each request. You can use any server log monitoring tool to find out which requested URL gives 503 service temporarily unavailable error. Once you have identified the problematic URLs, you can investigate further into the underlying cause.

Bonus Read : How to Increase File Upload Size in NGINX

5. Application Bugs

Based on previous step, once you have identified the requested URLs that return 503 service temporarily unavailable error, look for bugs in code or script that serve those URLs. Look into your version control system’s commit history for any recent modifications to the code that serves those URLs. This will help you identify and fix problems quickly.

Hopefully, the above tips will help you fix 503 service temporarily unavailable error in Apache.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

Related posts:

  • About Author

mm

Let’s fix the 503 Service Temporarily Unavailable in the NGINX server. Bobcares, as a part of our Server Management Service offers solutions to every query that comes our way.

503 Service Temporarily Unavailable in NGINX server

A popular HTTP status code that denotes the unavailability of a web server is 503, which stands for Service Temporarily Unavailable. It denotes that the server is presently unable to handle the request because of a brief overload or maintenance when it is encountered.

We will examine the root causes of the 503 error and efficient troubleshooting techniques to fix the problem with Nginx in this article.

503 Service Temporarily Unavailable in NGINX: Causes

The 503 error may occur for a number of reasons, such as high server demand, a lack of resources, connectivity problems with the backend servers, incorrect NGINX settings, or brief server maintenance. In order to apply the right repairs, it is essential to understand the underlying problem.

503 Service Temporarily Unavailable in NGINX: Troubleshooting

Some of the ways in which we can fix the issue are as follows:

1. Verify Nginx Configuration: To begin, check the Nginx configuration files and make sure the setup is correctxdswr]=]. Check the proxy settings, upstream setups, and server blocks. A 503 error may result from any configuration issue. Restart Nginx after making any necessary modifications.

2. Check the connectivity of the backend server: Verify that the backend servers are reachable and operating normally. Ping them or directly access them to check the connectivity. If we experience connectivity problems, fix them or ask the server administrators for help.

3. Modify the server’s load and resource limitations: Check the server’s resource usage and load. The 503 error can occur by high CPU usage, memory exhaustion, or disk space restrictions. If necessary, optimize the server’s code, scale its resources, or upgrade its hardware.

4. Verify the Proxy Settings: Verify the proxy settings if Nginx is being used as a reverse proxy. Verify the proxy directives are in place and that the upstream servers are configured correctly. Restart Nginx after making any necessary changes.

5. Increasing Server Timeout Values: Increase the timeout parameters in Nginx’s configuration to give backend servers additional time to react. According to the needs, increase the proxy timeout, client timeout, or other pertinent timeout settings.

[Looking for a solution to another query? Click here to reach us.]

Conclusion

We can also set up health checks to regularly monitor the status of backend servers, which in turn reduces the possibility of 503 Service Temporarily Unavailable in the NGINX server

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

I’m setting up nginx-proxy as a reverse proxy in front of Docker container running an app server. They’re defined in separate Docker compose definitions. For some reason I’m getting a 503, but I don’t know why and I’ve gone over the nginx-proxy docs in detail.

(I’ve also opened this as a github issue for nginx-proxy.)

The app server originally served https over 443 with 10443 exposed on the host. I switched to serving http over 80 with 10443 exposed on the host.

I can curl from the app server directly, but curling through nginx-proxy throws up an error

I initially had nginx-proxy on 443, but I switched it to 80 for now.

Until I added default.crt and default.key, I was getting a connection refused error. After adding them, I’m getting a 503.

curl http://foo.example.com:80/apidocs --verbose --insecure
* Hostname was NOT found in DNS cache
*   Trying 10.x.x.x...
* Connected to foo.example.com (10.x.x.x) port 80 (#0)
> GET /apidocs HTTP/1.1
> User-Agent: curl/7.35.0
> Host: foo.example.com
> Accept: */*
>
< HTTP/1.1 503 Service Temporarily Unavailable
* Server nginx/1.9.12 is not blacklisted
< Server: nginx/1.9.12
< Date: Thu, 21 Apr 2016 17:26:16 GMT
< Content-Type: text/html
< Content-Length: 213
< Connection: keep-alive
<
<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>nginx/1.9.12</center>
</body>
</html>
* Connection #0 to host foo.example.com left intact

Here’s my compose definition for nginx-proxy. I’m using network_mode: bridge which is supposed to work even with version: 2.

version: '2'
# Not yet compatible with custom networks in v2 of Compose
services:
  nginx:
    image: jwilder/nginx-proxy
    # Necessary until nginx-proxy fully supports Compose v2 networking
    network_mode: bridge
    ports:
      - "80:80"
    restart: always
    volumes:
      - "certs:/etc/nginx/certs:ro"
      - "nginx-log:/var/log/nginx"
      - "/var/run/docker.sock:/tmp/docker.sock:ro"
volumes:
  certs:
    external: true
  nginx-log:
    external: true

Here’s my app server composition:

version: '2'
services:
  database:
    image: sameersbn/postgresql:9.4-13
    restart: always
    # Necessary until nginx-proxy fully supports Compose v2 networking
    network_mode: bridge
    ports:
      - "55433:5432"
    environment:
      - DB_USER=foo
      - DB_PASS=...
      - DB_NAME=foo_staging
      - USERMAP_UID=1000
    volumes:
      - "foo-data:/var/lib/postgresql"

  foo:
    image: private-registry.example.com/dswb/foo:1.4.3
    restart: always
    container_name: "dswb-foo"
    links:
      - "database:database"
    # Necessary until nginx-proxy fully supports Compose v2 networking
    network_mode: bridge
    ports:
      - "10443:80"
    volumes:
      - "certs:/home/rails/webapp/certs"
    environment:
#      - "CERT_NAME=example.com"
      - "VIRTUAL_HOSTNAME=foo.example.com"
      - "VIRTUAL_PORT=80"
      - "VIRTUAL_PROTO=http"
    command: "bash -c 'rake db:migrate && thin --port 80 --address 0.0.0.0 start'"
volumes:
  foo-data:
    driver: local
  certs:
    external: true

The certs are less relevant since I switched to port 80 to debug. I have a wildcard certificate for *.example.com. I made a copy named foo.example.com in case nginx-proxy couldn’t find it. I tried both setting and not setting CERT_NAME. I’ve now also generated the dhparam stuff.

root@8b02a7deb220:/etc/nginx/certs# ls -la
total 48
drwxr-xr-x 2 root root 4096 Apr 21 18:15 .
drwxr-xr-x 4 root root 4096 Apr 21 18:06 ..
-rw------- 1 root root 3575 Apr 21 18:03 example.com.crt
-rw-r--r-- 1 root root  769 Apr 21 18:03 example.com.dhparam.pem
-rw------- 1 root root 1679 Apr 21 18:03 example.com.key
-rw-r--r-- 1 root root 1838 Apr 21 18:03 default.crt
-rw-r--r-- 1 root root 3268 Apr 21 18:03 default.key
-rw------- 1 root root 3575 Apr 21 17:37 foo.example.com.crt
-rw-r--r-- 1 root root  769 Apr 21 18:15 foo.example.com.dhparam.pem
-rw------- 1 root root 1679 Apr 21 17:37 foo.example.com.key

This is the only thing that shows up in the nginx-proxy log when I curl:

nginx.1    | foo.example.com 10.x.x.x - - [21/Apr/2016:17:26:16 +0000] "GET /apidocs HTTP/1.1" 503 213 "-" "curl/7.35.0"

Nothing shows up in app server log, meaning it does not see the request.

How do I debug this? Are there better logs somewhere?

Время на прочтение
7 мин

Количество просмотров 30K

Работа в поддержке хостинга в основном однотипная, большинство запросов от клиентов решаются по проработанной схеме, но иногда всё же приходится сталкиваться с нетривиальными проблемами. Тогда главная задача инженера — найти тот самый — единственно верный путь, который приведёт к её решению. В этой статье хочу рассказать о том, как мы столкнулись с плавающей ошибкой «HTTP Error 503. Service Unavailable» на нашем shared-хостинге, как пытались её отловить, провели диагностику и получили неожиданный финал.

Начало

Хостинг предоставляет пользователям типичный стек Linux + Apache + Mysql + PHP и оболочку для управления. В нашем случае это ISP Manager 5 business на базе Centos 7 с конвертацией в CloudLinux. Со стороны административной части, CloudLinux предоставляет инструменты для управления лимитами, а так же PHP-селектор с различными режимами работы (CGI, FastCGI, LSAPI).

В этот раз к нам обратился клиент со следующей проблемой. Его сайт на движке WordPress периодически начал отдавать 503 ошибку, о чём он нам и сообщил.

Коды ответа, начинающиеся с 50х, относятся к проблемам на стороне сервера. Это могут быть проблемы как самого сайта, так и веб-сервера, который их обслуживает.

Типичные ситуации, при которых мы получаем следующие ошибки:

  • 500 Internal Server Error — довольно часто связана либо с синтаксическими ошибками в коде сайта, либо с отсутствующими библиотеками / не поддерживаемой версией PHP. Так же могут быть проблемы с подключением к базе данных сайта или неверными правами на файлы / каталоги
  • 502 Bad Gateway — например, если Nginx ссылается на неправильный порт веб-сервера Apache или процесс Apache по какой-то причине перестал работать
  • 504 Gateway Timeout — ответ от Apache не был получен в течение заданного в конфигурации веб-сервера времени
  • 508 Resource limit is reached — превышен лимит, выделяемых пользователю ресурсов

В данном списке приведены лишь некоторые, наиболее распространённые случаи. Также стоит отметить, что при превышении лимитов пользователь может получить как 500, так и 503 ошибку.

При выполнении диагностики данных ошибок, первым делом проверяем журналы веб-сервера. Обычно, этого достаточно, чтобы определить виновника и исправить проблему.

Касаемо 503 ошибки в нашем случае, в логах мы видели запись:

[lsapi:error] [pid 49817] [client x.x.x.x:6801] [host XXX.XX] Error on sending request(GET /index.php HTTP/1.0); uri(/index.php) content-length(0): ReceiveAckHdr: nothing to read from backend (LVE ID 8514), check docs.cloudlinux.com/mod_lsapi_troubleshooting.html

На основании только этого лога, определить в чём может быть проблема не представлялось возможным.

Первичная диагностика

Изначально, мы проверили статистику превышения лимитов пользователем. Незначительные превышения были зафиксированы за предыдущие дни, но ошибки в журналах были свежие, более того они появлялись в журнале с периодичностью от одной до нескольких минут.

Так же мы изучили рекомендации CloudLinux, по приведённой в журналах ошибок ссылке.
Изменение каких-либо параметров результата не принесло.

Сайт использовал базу данных на сервере Mysql 5.7, который работает на этом же сервере в контейнере Docker. В логах контейнера присутствовали сообщения:

[Note] Aborted connection 555 to db: 'dbname' user: 'username' host: 'x.x.x.x' (Got an error reading communication packets)

Как раз, среди этих сообщений были сообщения о прерванном подключении исследуемого сайта. Это дало предположение, о том, что подключение к СУБД выполняется некорректно. Для проверки мы развернули копию сайта на тестовом домене, сконвертировали базу данных сайта под нативную в Centos 7 версию СУБД 5.5.65-MariaDB. На тестовом сайте выполнили несколько сотен запросов с помощью утилиты curl. Ошибку воспроизвести не удалось. Но этот результат был предварительным и после конвертации БД на рабочем сайте проблема так и осталась.

Таким образом, проблема некорректного подключения к СУБД была исключена.

Следующим предположением было проверить — нет ли проблем с самим сайтом. Для этого подняли отдельный виртуальный сервер, на нём подняли максимально схожее окружение. Единственное существенное отличие — отсутствие CloudLinux. На тестовом сервере проблему воспроизвести не удалось. Итак, мы определили, что в коде сайта всё в порядке. Тем не менее, пробовали так же отключать плагины WordPress, но проблема так же сохранялась.

В результате, пришли к тому, что проблема на нашем хостинге.

В ходе анализа журналов других сайтов было обнаружено, что проблема наблюдается на многих из них. Порядка 100 шт. на момент проверки:

/var/www/httpd-logs# grep -Rl "ReceiveAckHdr: nothing to read from backend" ./ | wc -l
99

В ходе тестирования обнаружили, что только что установленная чистая CMS WordPress также периодически выдаёт ошибку 503.

Примерно за 2 месяца до этого мы проводили работы по модернизации сервера, в частности изменили режим работы Apache с Worker на Prefork, с целью получить возможность использовать PHP в режиме LSAPI, вместо медленного CGI. Было предположение, о том, что это могло повлиять, либо требуются какие-то дополнительные настройки Apache, но вернуть обратно режим Worker мы уже не могли. В ходе изменения режима работы Apache выполняется изменение всех конфигов сайтов, процесс не быстрый и не всё могло пройти гладко.

Корректировка настроек Apache так же не дала желаемого результата.

Попутно искали схожие проблемы в поисковых системах. На одном из форумов участники утверждали, что проблема у хостера и нужно его менять, если проблему не решают. Звучит не очень оптимистично, когда ты находишься с другой стороны, но и клиента понять можно. Зачем ему нерабочий хостинг.

На данном этапе мы собрали имеющуюся информацию и результаты проведённых работ. С ними обратились в поддержку CloudLinux.

Детальная диагностика

В течение нескольких дней сотрудники поддержки CloudLinux вникали в проблему. В основном рекомендации были относительно установленных лимитов пользователей. Этот вопрос мы так же проверяли. При отключенных лимитах (Опция CageFS для пользователя) и с включенными лимитами в режиме PHP как модуль Apache проблема не наблюдалась. Исходя из этого, было сделано предположение, что каким-то образом оказывает влияние CloudLinux. В итоге, к концу недели запрос был эскалирован на 3-ий уровень поддержки, но решения пока не было.

Попутно изучали документацию Apache по режимам работы CGI и LSAPI, подняли второй экземпляр Apache на сервере хостинга на другом порту с тестовым сайтом, исключили влияние Nginx, отправляя запросы напрямую к Apache и получая те же коды ошибок.

Сдвинуться с мёртвой точки помогла документация LSAPI, как раз по диагностике 503 ошибки:
www.litespeedtech.com/support/wiki/doku.php/litespeed_wiki:php:503-errors
В секции Advanced Troubleshooting предлагается выполнять трассировку найденных в системе процессов:

while true; do if mypid=`ps aux | grep $USERNAME | grep lsphp | grep $SCRIPTNAME | grep -v grep | awk '{print $2; }' | tail -1`; then strace -tt -T -f -p $mypid; fi ; done

Команда была доработана, с целью записи всех процессов в файлы с указанием их идентификаторов.

При просмотре файлов трассировок, мы видим в некоторых одинаковые строки:

cat trace.* | tail
...
47307 21:33:04.137893 --- SIGHUP {si_signo=SIGHUP, si_code=SI_USER, si_pid=42053, si_uid=0} ---
47307 21:33:04.140728 +++ killed by SIGHUP +++
...

Если взглянуть на описание структуры сигналов, отправляемых процессами, то увидим, что

pid_t    si_pid;       /* Sending process ID */

Указывает на идентификатор процесса, отправившего сигнал.

На момент изучения трассировок, процесса с PID 42053 в системе уже нет, поэтому в процессе захвата трассировок решили отслеживать так же процессы, отправившие сигнал SIGHUP.
Под спойлером описаны действия, которые позволили определить что это за процесс, а так же получить его трассировку и дополнительную информацию, о том, каким процессам он отправляет сигнал SIGHUP.

Методика трассировки

Консоль 1.

tail -f /var/www/httpd-logs/sitename.error.log

Консоль 2.

while true; do if mypid=`ps aux | grep $USERNAME | grep lsphp | grep "sitename" | grep -v grep | awk '{print $2; }' | tail -1`; then strace -tt -T -f -p $mypid -o /tmp/strace/trace.$mypid; fi ; done

Консоль 3.

while true; do if mypid=`cat /tmp/strace/trace.* | grep si_pid | cut -d '{' -f 2 | cut -d'=' -f 4 | cut -d',' -f 1`; then ps -aux | grep $mypid; fi; done;

Консоль 4.

seq 1 10000 | xargs -i sh -c "curl -I http://sitename/"

Ждём пока в консоли 1 появятся сообщения, при этом в консоли 4 видим статус запроса с кодом ответа 503, прерываем выполнение в консоли 4.

В итоге, получили название процесса /opt/alt/python37/bin/python3.7 -sbb /usr/sbin/cagefsctl --rebuild-alt-php-ini

Данный процесс выполнялся в системе с периодичностью раз в минуту.

Делаем трассировку нескольких процессов cagefsctl, чтобы отследить хотя бы один от начала до конца:

for i in `seq 1 100`; do strace -p $(ps ax | grep cagefsctl | grep rebuild-alt-php-ini | grep -v grep | awk '{print $1}') -o /tmp/strace/cagefsctl.trace.$(date +%s); done;

Далее изучаем что он делал, например:

cat /tmp/strace/cagefsctl.trace.1593197892 | grep SIGHUP

Так же были получены идентификаторы процессов, которые были завершены сигналом SIGHUP. Завершённые процессы были процессами PHP, выполняющимися в данный момент.

Полученные данные были переданы в поддержку CloudLinux с целью уточнить легитимность данного процесса и должен ли он работать с такой периодичностью.

Позже получили ответ, что работа команды /usr/sbin/cagefsctl --rebuild-alt-php-ini выполняется корректно, единственный нюанс в том, что команда выполняется слишком часто. Обычно вызывается при системном обновлении или изменении параметров PHP.

Единственная зацепка в данном случае осталась — проверить, кто является родительским процессом cagefsctl.

Результат не заставил себя долго ждать и какого же было наше удивление — родительским процессом для cagefsctl являлся процесс ispmgrnode. Это было немного странно, потому что уровень журналирования для ISP Manager был задан максимальным и в ispmgr.log не увидели вызов cagefsctl.

Теперь данных было достаточно, чтобы обратиться и в поддержку ISP System.

Итоги

Проблема была спровоцирована после выполнения обновления ISP Manager. В целом, обновление ISP Manager — штатная ситуация, но она привела к запуску процесса синхронизации, который завершался с ошибкой и перезапускался ежеминутно. Процесс синхронизации вызывал за собой процесс cagefsctl, который в свою очередь завершал процессы PHP.

Причиной зависания процесса синхронизации стали проведённые на хостинге работы по модернизации оборудования. За несколько месяцев до возникновения проблемы, в сервер был установлен PCI-e NVMe-накопитель, создан раздел XFS и смонтирован в каталог /var. На него были перенесены в том числе и файлы пользователей, но не обновились дисковые квоты. Опций монтирования было не достаточно, требовалось так же изменить тип файловой системы в параметрах ISP Manager, т.к. она вызывает команды обновления дисковых квот. Для Ext4 и XFS эти команды отличаются.

Таким образом, проблема дала о себе знать спустя несколько месяцев после проведения работ.

Выводы

Мы сами создали проблему, но это было не ясно до последнего момента. На будущее, будем стараться учесть как можно больше нюансов. Благодаря помощи более подготовленных коллег из поддержки CloudLinux и ISP System, проблема была решена. Теперь наш хостинг работает стабильно. А нами был получен опыт, который пригодится нам в будущей работе.

P.S.: Надеюсь, Вам было интересно ознакомиться с материалом статьи, а кому-нибудь она поможет быстрее решить подобную проблему.

I’m setting up nginx-proxy in front of an app server. They’re defined in separate compose definitions. For some reason I’m getting a 503, but I don’t know why and I’ve gone over the nginx-proxy docs in detail.

The app server originally served https over 443 with 10443 exposed on the host. I switched to serving http over 80 with 10443 exposed on the host.

I can curl from the app server directly, but curling through nginx-proxy throws up an error

I initially had nginx-proxy on 443, but I switched it to 80 for now.

Until I added default.crt and default.key, I was getting a connection refused error. After adding them, I’m getting a 503.

curl http://foo.example.com:80/apidocs --verbose --insecure
* Hostname was NOT found in DNS cache
*   Trying 10.x.x.x...
* Connected to foo.example.com (10.x.x.x) port 80 (#0)
> GET /apidocs HTTP/1.1
> User-Agent: curl/7.35.0
> Host: foo.example.com
> Accept: */*
>
< HTTP/1.1 503 Service Temporarily Unavailable
* Server nginx/1.9.12 is not blacklisted
< Server: nginx/1.9.12
< Date: Thu, 21 Apr 2016 17:26:16 GMT
< Content-Type: text/html
< Content-Length: 213
< Connection: keep-alive
<
<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>nginx/1.9.12</center>
</body>
</html>
* Connection #0 to host foo.example.com left intact

Here’s my compose definition for nginx-proxy. I’m using network_mode: bridge which is supposed to work even with version: 2.

version: '2'
# Not yet compatible with custom networks in v2 of Compose
services:
  nginx:
    image: jwilder/nginx-proxy
    # Necessary until nginx-proxy fully supports Compose v2 networking
    network_mode: bridge
    ports:
      - "80:80"
    restart: always
    volumes:
      - "certs:/etc/nginx/certs:ro"
      - "nginx-log:/var/log/nginx"
      - "/var/run/docker.sock:/tmp/docker.sock:ro"
volumes:
  certs:
    external: true
  nginx-log:
    external: true

Here’s my app server composition:

version: '2'
services:
  database:
    image: sameersbn/postgresql:9.4-13
    restart: always
    # Necessary until nginx-proxy fully supports Compose v2 networking
    network_mode: bridge
    ports:
      - "55433:5432"
    environment:
      - DB_USER=foo
      - DB_PASS=...
      - DB_NAME=foo_staging
      - USERMAP_UID=1000
    volumes:
      - "foo-data:/var/lib/postgresql"

  foo:
    image: private-registry.example.com/dswb/foo:1.4.3
    restart: always
    container_name: "dswb-foo"
    links:
      - "database:database"
    # Necessary until nginx-proxy fully supports Compose v2 networking
    network_mode: bridge
    ports:
      - "10443:80"
    volumes:
      - "certs:/home/rails/webapp/certs"
    environment:
#      - "CERT_NAME=example.com"
      - "VIRTUAL_HOSTNAME=foo.example.com"
      - "VIRTUAL_PORT=80"
      - "VIRTUAL_PROTO=http"
#    command: "bash -c 'rake db:migrate && thin --ssl --ssl-key-file certs/star_example_com.key --ssl-cert-file certs/star_example_com.bundle.crt --port 443 --address 0.0.0.0 start'"
    command: "bash -c 'rake db:migrate && thin --port 80 --address 0.0.0.0 start'"
volumes:
  foo-data:
    driver: local
  certs:
    external: true

The certs are less relevant since I switched to port 80 to debug. I have a wildcard certificate for *.example.com. I made a copy named foo.example.com in case nginx-proxy couldn’t find it. I tried both setting and not setting CERT_NAME. I’ve now also generated the dhparam stuff.

root@8b02a7deb220:/etc/nginx/certs# ls -la
total 48
drwxr-xr-x 2 root root 4096 Apr 21 18:15 .
drwxr-xr-x 4 root root 4096 Apr 21 18:06 ..
-rw------- 1 root root 3575 Apr 21 18:03 example.com.crt
-rw-r--r-- 1 root root  769 Apr 21 18:03 example.com.dhparam.pem
-rw------- 1 root root 1679 Apr 21 18:03 example.com.key
-rw-r--r-- 1 root root 1838 Apr 21 18:03 default.crt
-rw-r--r-- 1 root root 3268 Apr 21 18:03 default.key
-rw------- 1 root root 3575 Apr 21 17:37 foo.example.com.crt
-rw-r--r-- 1 root root  769 Apr 21 18:15 foo.example.com.dhparam.pem
-rw------- 1 root root 1679 Apr 21 17:37 foo.example.com.key

This is the only thing that shows up in the nginx-proxy log when I curl:

nginx.1    | foo.example.com 10.x.x.x - - [21/Apr/2016:17:26:16 +0000] "GET /apidocs HTTP/1.1" 503 213 "-" "curl/7.35.0"

Nothing shows up in app server log, meaning it does not see the request.

How do I debug this? Are there better logs somewhere?

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • 5029 ошибка терминал сбербанк
  • 502 ошибка ddos
  • 502 ошибка bitrixvm
  • 503 ошибка bitrix
  • 502 неисправный шлюз это ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии