Ошибка разрешения в NGINX и Gunicorn в Docker: ошибка подключения () к unix: /tmp/gunicorn.sock (13: разрешение запрещено) при подключении к восходящему каналу - PullRequest
1 голос
/ 18 октября 2019

У меня запущено приложение Python Flask с компоновкой Gunicorn, NGINX и Docker. Я получаю следующую ошибку при отправке HTTP POST. Я запускаю это на хосте Linux Mint.

nginx_1   | 127.0.0.1 - - [18/Oct/2019:20:49:47 +0000] "GET /v1/simulations HTTP/1.1" 502 157 "-" "PostmanRuntime/7.18.0"
nginx_1   | 2019/10/18 20:49:47 [crit] 6#6: *1 connect() to unix:/tmp/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: example.com, request: "GET /v1/simulations HTTP/1.1", upstream: "http://unix:/tmp/gunicorn.sock:/v1/simulations", host: "localhost:5000"

docker-compose.yml:

version: "3"
services:
  server:
    image: grip-server_server
    build:
      context: .
      args:
        GRIP_ENVSET: ${GRIP_ENV}
    volumes:
      - ".:/gripcode"
      - "/tmp:/tmp"
      # Mount the Docker socket so that other Docker images can be started up.
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/tmp/gunicorn.sock:/tmp/gunicorn.sock"
    environment:
      - PORT=5005
      - GRIP_ENV=${GRIP_ENV}
      - JWT_ACCESS_TOKEN_EXPIRES=${JWT_ACCESS_TOKEN_EXPIRES}
      - JWT_REFRESH_TOKEN_EXPIRES=${JWT_REFRESH_TOKEN_EXPIRES}
      - DOCKER_HOST=${DOCKER_HOST}
    network_mode: host
    depends_on:
      - redis
      - celery
      - nginx
    # Listening on port 5005
  nginx:
    # restart: always
    build: ./nginx
    ports:
      - "5000:5005"
    volumes:
       # - .:/www/static
       # - web-data:gripcode
      - ".:/gripcode"
      - "/tmp:/tmp"
      - "/tmp/gunicorn.sock:/tmp/gunicorn.sock"
    network_mode: host
    # Listening on port 5000
  redis:
    image: redis
    restart: on-failure
    container_name: redis
    network_mode: host
    # Listening on 6379
  #rabbitmq:
  #  image: rabbitmq:3
  #  restart: on-failure
  #  container_name: redis
  #  network_mode: host
  #  # Listening on 5672 and 15672
  #  #environment:
  #    #- redis_DEFAULT_USER=user
  #    #- redis_DEFAULT_PASS=password
  celery:
    image: grip-server_celery
    build: .
    restart: on-failure
    command: bash -c "bash ./bin/wait_for_broker.sh && bash ./bin/fix_celery_naming.sh && celery -E -A components.grip_sim_api_server.server.celery worker --pool gevent" # Debugging: -l debug
    volumes:
      - .:/gripcode
      - "/tmp:/tmp"
      - "/var/run/docker.sock:/var/run/docker.sock" # To be able to start the GridLAB-D docker image
    network_mode: host
    depends_on:
      - redis
    environment:
      - CELERY_BROKER_URL=redis://127.0.0.1:6379
      - CELERY_RESULT_BACKEND=redis://127.0.0.1:6379
      #- CELERY_BROKER_URL=amqp://guest:guest@localhost:5672
      #- CELERY_RESULT_BACKEND=amqp://localhost
      - DOCKER_HOST=${DOCKER_HOST}
      - DEBUG_CELERY=${DEBUG_CELERY} # True to enable remote debugging
      - CELERY_RDB_PORT=${CELERY_RDB_PORT}
    tty: true
  omf:
    image: presence/omf:latest
    restart: on-failure
    #build:
    #  context: .
    #  args:
    #    GRIP_ENVSET: ${GRIP_ENV}
    working_dir: /home/omf/omf/scratch/GRIP
    command: grip.py
    network_mode: host
    # Listening on port 5100
  flower:
    #image: mher/flower
    image: grip-server_flower
    build: .
    restart: on-failure
    command: bash -c "bash ./bin/wait_for_broker.sh && flower -A components.grip_sim_api_server.server.celery worker --address=0.0.0.0 --port=5555 --logging=debug --pool gevent"
    working_dir: /gripcode
    volumes:
      - .:/gripcode
    depends_on:
      - redis
      - celery
    environment:
      - CELERY_BROKER_URL=redis://127.0.0.1:6379
      - CELERY_RESULT_BACKEND=redis://127.0.0.1:6379
      #- CELERY_BROKER_URL=amqp://guest:guest@localhost:5672
      #- CELERY_RESULT_BACKEND=amqp://guest:guest@localhost:5672
    network_mode: host
    # Listening on port 5555
    network_mode: host

Dockerfile:

FROM library/python:3.7-stretch


RUN apt-get update && apt-get install -y python3 python3-pip \
    postgresql-client \
    # TODO - Might not need this any longer with GridLAB-D on its own container
    # GridLAB-D requires this library
    # libxerces-c-dev \
    # For VIM
    apt-file  \
    vim \
    #for Docker (spin up another Docker container sibling from inside this container)
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg2 \
    software-properties-common \
    #python3-distutils
    python-distutils-extra

#RUN yes | apt-get install rabbitmq-server

# Install Docker, to be able to run sibling docker containers
RUN add-apt-repository \

. / Nginx /Dockerfile:

#FROM tutum/nginx
FROM nginx:1.17.4

#RUN rm /etc/nginx/sites-enabled/default
#COPY sites-enabled/ /etc/nginx/sites-enabled

COPY nginx.conf /etc/nginx

# RUN chown -R nginx:nginx /etc/nginx
RUN chown -R ${USER}:${USER} /etc/nginx

. / Nginx / nginx.conf:

worker_processes 1;

user nobody nogroup;
# 'user nobody nobody;' for systems with 'nobody' as a group instead
error_log  /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
  worker_connections 1024; # increase if you have lots of clients
  accept_mutex off; # set to 'on' if nginx worker_processes > 1
  # 'use epoll;' to enable for Linux 2.6+
  # 'use kqueue;' to enable for FreeBSD, OSX
}

http {
  include mime.types;
  # fallback in case we can't determine a type
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log combined;
  sendfile on;

  upstream app_server {
    # fail_timeout=0 means we always retry an upstream even if it failed
    # to return a good HTTP response

    # for UNIX domain socket setups
    server unix:/tmp/gunicorn.sock fail_timeout=0;

    # for a TCP configuration
    # server 192.168.0.7:8000 fail_timeout=0;
  }

  #server {
  #  # if no Host match, close the connection to prevent host spoofing
  #  listen 80 default_server;
  #  return 444;
  #}

  server {
    # use 'listen 80 deferred;' for Linux
    # use 'listen 80 accept_filter=httpready;' for FreeBSD
    listen 5000;
    client_max_body_size 4G;

    # set the correct host(s) for your site
    server_name example.com www.example.com;

    keepalive_timeout 5;

    # path for static files
    # root /path/to/app/current/public;

    location / {
      # checks for static file, if not found proxy to app
      try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      # we don't want nginx trying to do something clever with
      # redirects, we set the Host: header above already.
      proxy_redirect off;
      proxy_buffering off;
      proxy_pass http://app_server;
    }

    # error_page 500 502 503 504 /500.html;
    # location = /500.html {
    #  root /path/to/app/current/public;
    #}
  }
}

1 Ответ

0 голосов
/ 26 октября 2019

Я настроил привязку порта ("5000: 5005") и сеть хоста в главном файле компоновки Docker. В Mac я работал над тем, чтобы удалить привязку порта в главном файле, просто сохранить сеть хоста в главном файле, а затем в файле переопределения Mac Docker Compose переопределить сеть хоста с сетью моста по умолчанию,затем добавьте привязку порта в файл переопределения Docker Compose для Mac.

Другая проблема заключалась в том, что я пытался выполнить это сопоставление порта 5000 с портом 5005 в Docker Compose, но это фактически является обязанностью NGINX. конфигурации. Все, что мне нужно было сделать в Docker, - это открыть порты для NGINX и приложения Flask / Gunicorn. Это было сделано неявно с помощью сети хоста в основном файле (5000: 5000, поскольку я использовал порт NGINX не по умолчанию) и явно в файле переопределения Mac Docker Compose с использованием привязки порта (5005: 5005 для Gunicorn / Flask, также непорт по умолчанию). Затем NGINX перевернул прокси с 5000 (NGINX) до 5005 (Gunicorn) в зависимости от конфигурации NGINX. Это было через контейнеры Docker.

...