3

I'm having a docker image with nginx.

I would like to log incoming requests.

My docker-compose file:

nginx:
  container_name: my-nginx
image: nginx
ports:
  - "80:80"
  - "443:443"
volumes:
  - ./nginx.conf:/etc/nginx/conf.d/default.conf
  - ./access.log:/var/log/nginx/test.com.access.log

My nginx config:

server {
 listen 80;
 listen 443 default_server ssl;
 access_log /var/log/nginx/test.com.access.log;

 location / {
  proxy_pass http://myapp:8080;
  proxy_buffering off;
 }
}

When I try to replace access_log directive with following config:

log_format testlog '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $bytes_sent '
                   '"$http_referer" "$http_user_agent" "$request_body"';
access_log /var/log/nginx/test.com.access.log testlog;

I'm getting:

nginx-reverse-proxy | 2018/04/06 11:50:00 [emerg] 1#1: "log_format" directive is not allowed here in /etc/nginx/conf.d/default.conf:10
nginx-reverse-proxy | nginx: [emerg] "log_format" directive is not allowed here in /etc/nginx/conf.d/default.conf:10
pixel
  • 24,905
  • 36
  • 149
  • 251
  • You shouldn't have listeners for HTTP and HTTPS in the same server block, but instead create a separate one for HTTPS including the needed SSL keys. – Niels de Bruin Apr 06 '18 at 12:08

2 Answers2

5

Put the log_format outside the server{} block, because not every directive can go anywhere. Simply:

log_format testlog '$remote_addr - $remote_user [$time_local] '
               '"$request" $status $bytes_sent '
               '"$http_referer" "$http_user_agent" "$request_body"';

server {
 listen 80;
 listen 443 default_server ssl;
 access_log /var/log/nginx/test.com.access.log;

 location / {
  proxy_pass http://myapp:8080;
  proxy_buffering off;
 }
}

It is docuemnted here: http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format "Context: http"

http context is the top level block, the one that contains your server block (usually you don't see it because it is in another file that is including your .conf)

Robert
  • 33,429
  • 8
  • 90
  • 94
0

This seems to be a duplicate of this question.

The message means that you have an http directive somewhere it's not allowed, i.e.

http {
    ...
}

You probably want to use a server block instead, i.e.

server {
    listen 80 default_server;
    server_name test.com;
    root /var/www/test/;
    access_log /var/log/nginx/test.com.access.log;
}
Niels de Bruin
  • 705
  • 5
  • 15