Nginx не настроен и неактивен после обновления платформы AL2 Docker до новейшей версии

У нас есть докеризованное Django-приложение на Elastic Beanstalk, работающее на ныне устаревшей платформе AMI, развернутое через EB CLI. Я единственный технический сотрудник и только недавно унаследовал эту среду, практически без передачи и без опыта работы с AWS.

Когда я впервые развернул новую среду на платформе AL2 Docker 3.5.0, следуя руководству по обновлению от Amazon, новые экземпляры появились и сразу же провалили все проверки работоспособности. Оказалось, что служба nginx неактивна, а все примененные конфигурационные файлы - это просто nginx по умолчанию, и ни EB platform defaults, ни .conf файлы, которые я поместил в .platform/nginx/conf.d/elasticbeanstalk, не присутствуют. Просто запуск службы nginx позволяет успешно проверить здоровье, но поскольку конфигурация отсутствует, все, что она показывает, это стандартную страницу приветствия nginx.

После некоторых проб и ошибок я попробовал клонировать среду, затем понизить ее до AL2 Docker 3.0.3. После развертывания на пониженной платформе все работает из коробки. Основная разница, которую я вижу между 3.0.3 и 3.5.0, это переход с версии docker 19.03 на 20.10 (ref), и nginx с 1.16 на 1.20. Затем я попробовал последнюю доступную версию платформы, которая все еще использовала docker 19, а именно AL2 3.2.2, под управлением nginx 1.18. Получилось то же поведение, что и на платформе 3.5.0 (отсутствует конфиг, nginx неактивен).

Я попробовал вручную продублировать файл /etc/nginx/nginx.conf на 3.5.0 с 3.0.3, а затем вручную запустить службу nginx, но это привело к ошибке 502 (плохой шлюз).

Моя ОС разработки - windows, поэтому на всякий случай я убедился, что окончания строк всех конфигурационных файлов - просто LF, а не CRLF. Никаких изменений. Я также пробовал восстанавливать окружение, проклинать отдельные экземпляры до седьмого поколения и тихо плакать в кабинке туалета.

Далее следует дамп данных всего, что я смог вспомнить.

nginx.conf на AL2 Docker 3.0.3:


# Elastic Beanstalk Nginx Configuration File

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

events {
worker_connections  1024;
}

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

    access_log    /var/log/nginx/access.log;
    
    
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"';
    
    include  conf.d/*.conf;
    
    map $http_upgrade $connection_upgrade {
            default       "upgrade";
    }
    server {
        listen 80;
        gzip on;
        gzip_comp_level 4;
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    
        access_log    /var/log/nginx/access.log main;
    
        location / {
            proxy_pass            http://docker;
            proxy_http_version    1.1;
    
            proxy_set_header    Connection             $connection_upgrade;
            proxy_set_header    Upgrade                $http_upgrade;
            proxy_set_header    Host                   $host;
            proxy_set_header    X-Real-IP              $remote_addr;
            proxy_set_header    X-Forwarded-For        $proxy_add_x_forwarded_for;
        }
    
        # Include the Elastic Beanstalk generated locations
        include conf.d/elasticbeanstalk/*.conf;
    }

}

nginx.conf на AL2 Docker 3.5.0:


# 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 4096;
    
    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;
    
    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
    
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
    
        error_page 404 /404.html;
        location = /404.html {
        }
    
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

Прослушивание портов (netstat -tulnp) из контейнера docker на AL2 Docker 3.0.3:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name     tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN      1/python            

Прослушивание портов (netstat -tulnp) из контейнера docker на AL2 Docker 3.5.0:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name     tcp        0      0 127.0.0.11:37505        0.0.0.0:*               LISTEN      -                    udp        0      0 127.0.0.11:38196        0.0.0.0:*                           -                   

Dockerfile:

FROM python:3.7

RUN apt-get update && apt-get install -y --no-install-recommends apt-utils
RUN apt-get -y upgrade && apt-get -y dist-upgrade

RUN pip install --upgrade pip

COPY requirements.txt /tmp/requirements.txt
RUN pip install -r /tmp/requirements.txt

RUN mkdir -p /code/staticfiles
COPY . /code/

WORKDIR /code
ENV DJANGO_SETTINGS_MODULE rebutia_web.settings
ENV PYTHONPATH "${PYTHONPATH}:src"

RUN python manage.py collectstatic --no-input

EXPOSE 8000

CMD \["./script/\[project_name\]"\]

docker-compose.yml:

version: '2'

services:
  web:
    build: .
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    environment:
      - [some django env variables]

результат select-string -pattern nginx (grep) всех журналов на 3.5.0:

eb-cfn-init.log:592:  inflating: /opt/elasticbeanstalk/config/private/healthd/healthd_nginx.conf
eb-cfn-init.log:602:  inflating: /opt/elasticbeanstalk/config/private/nginx/applicationport.conf.template
eb-cfn-init.log:603:  inflating: /opt/elasticbeanstalk/config/private/nginx/nginx.conf.template
eb-cfn-init.log:604:  inflating: /opt/elasticbeanstalk/config/private/nginx/staticfilesmapping.conf.template
eb-cfn-init.log:605:  inflating: /opt/elasticbeanstalk/config/private/nginx/elasticbeanstalk-nginx-docker-upstream.template
eb-cfn-init.log:606:  inflating: /opt/elasticbeanstalk/config/private/nginx/nginx.template
eb-engine.log:879:2022/11/03 15:32:59.848525 [INFO] Executing instruction: configure proxy Nginx
eb-engine.log:880:2022/11/03 15:32:59.850370 [INFO] Running command /bin/sh -c cp -rp /var/app/staging/.platform/nginx/. /var/proxy/staging/nginx
eb-engine.log:894:2022/11/03 15:33:00.337051 [INFO] Copying file /opt/elasticbeanstalk/config/private/healthd/healthd_logformat.conf to /var/proxy/staging/nginx/conf.d/healthd_logformat.conf
eb-engine.log:895:2022/11/03 15:33:00.339424 [INFO] Copying file /opt/elasticbeanstalk/config/private/healthd/healthd_nginx.conf to /var/proxy/staging/nginx/conf.d/elasticbeanstalk/healthd.conf

Я занимаюсь этим уже несколько дней и нахожусь в недоумении, и в то же время чувствую, что ответ, вероятно, кричаще очевиден. Что я упускаю? Я не чувствую, что ограничение приложения версией платформы 3.0.3 и отказ от всех обновлений - это приемлемый вариант.

Вернуться на верх