将Docker Nginx访问日志存储在Docker卷中

时间:2019-02-27 18:56:15

标签: docker nginx docker-compose

当前,我的Docker容器正在将Nginx访问日志打印到/ dev / stdout。如何在Docker容器中创建一个卷来存储访问日志?

我的Dockerfile:

FROM python:3.7

ENV APP_ROOT /src
ENV CONFIG_ROOT /config

RUN apt-get update
RUN apt-get install -y apt-utils
RUN apt-get -y install unixodbc-dev
RUN apt-get -y install default-libmysqlclient-dev

RUN mkdir ${CONFIG_ROOT}
COPY /app/requirements.txt ${CONFIG_ROOT}/requirements.txt
RUN pip install -r ${CONFIG_ROOT}/requirements.txt

RUN mkdir ${APP_ROOT}
WORKDIR ${APP_ROOT}

ADD /app/ ${APP_ROOT}

我的docker-compose.yml:

version: "3"

services:
  app:
    build: .
    container_name: django-gunicorn
    restart: always
    env_file:
      - django.env
    ports:
      - "8000:8000"
    command:
      "gunicorn --workers=2 --bind=0.0.0.0:8000 mysite.wsgi:application"

  nginx:
    image: nginx:1.14
    container_name: ngx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx:/etc/nginx/conf.d
      - ./app/static:/static
    depends_on:
      - app

我的nginx / default.conf:

limit_req_zone "$binary_remote_addr$request_uri" zone=one:10m rate=60r/m;

server {
    listen 80;
    server_name example.org;
    server_tokens off;

    location  /static/ {
        autoindex on;
        alias /static/;
    }

    location / {
        proxy_pass http://app:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        limit_req zone=one nodelay burst=30;

    }
}

我正在尝试向此应用程序添加fail2ban和流利的日志记录,但是首先我需要存储可用于其他日志记录目的的物理文件(不是/ dev / stout)。

谢谢!

2 个答案:

答案 0 :(得分:1)

默认情况下,Nginx容器将访问日志转发到STDOUT,将错误日志转发到STDERR。您可以在nginx Dockerfile中看到以下几行:

# forward request and error logs to docker log collector
    && ln -sf /dev/stdout /var/log/nginx/access.log \
    && ln -sf /dev/stderr /var/log/nginx/error.log \

因此您可以在容器日志中看到nginx日志:

docker logs -f ngx

但是,如果要将nginx日志存储在docker卷中,请首先创建自定义的nginx docker映像:

FROM nginx
RUN rm /var/logs/nginx/*

然后您在docker-compose.yml中的nginx服务将如下:

nginx:
    build: ./nginx/
    container_name: ngx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx:/etc/nginx/conf.d
      - ./app/static:/static
      - ./log/nginx:/var/log/nginx
    depends_on:
      - app

答案 1 :(得分:0)

除了上面的注释以添加卷之外,您还需要调整每个虚拟主机的主要Nginx配置(很可能是/etc/nginx/nginx.conf)和/或配置文件。

在大多数情况下,请将它们添加到您的主要配置中:

http {
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
}

类似的条目可能是serverlocation内的地方