Configuring Nginx to Split Daily Logs and Align Timezone Using Docker Compose and Dockerfile
This article explains how to configure Nginx to split access logs by day using the $time_iso8601 variable, align log timestamps with the local timezone via Docker‑Compose or Dockerfile settings, and introduces the GoAccess tool for visual log analysis.
After noticing that Nginx logs accumulate in a single file over long periods, the author describes a method to split logs by day, making log inspection easier.
By adding a $time_iso8601 variable and a map directive in nginx.conf , the access log path can be set to /var/log/nginx/access-$logdate.log , where $logdate is derived from the ISO‑8601 timestamp.
<code>user nginx;
worker_processes 2;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_iso8601] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" $request_time $upstream_response_time';
map $time_iso8601 $logdate {
'~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
default 'date-not-found';
}
access_log /var/log/nginx/access-$logdate.log main;
open_log_file_cache max=10;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
server_tokens off;
}</code>The author prefers $time_iso8601 over $time_local because its format ( 2023-03-29T16:58:49+08:00 ) is more readable.
To make the log timestamps match the local timezone, two approaches are shown. The first uses docker-compose to set the TZ environment variable:
<code>version: '3'
services:
d_nginx:
container_name: c_nginx
environment:
TZ: 'Asia/Shanghai'</code>The second embeds the timezone in the Docker image via a Dockerfile :
<code>FROM nginx:1.20.1-alpine
ENV TZ=Asia/Shanghai</code>For older Alpine‑based Nginx images, the tzdata package may be missing, so the Dockerfile installs it and creates the proper link:
<code>FROM nginx:1.12.1-alpine
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
ENV TZ=Asia/Shanghai
RUN apk add --update tzdata
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo '$TZ' > /etc/timezone</code>After these steps, the Nginx logs display the desired date format and correct timezone.
The article also recommends the goaccess tool for quick, visual analysis of Nginx logs, showing how to generate an HTML report:
<code>goaccess nginx.log -a > nginx.html</code>Overall, the guide provides a practical solution for daily log rotation, timezone alignment, and log analysis for Nginx deployments.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.