logrotate.j2

Overview

The logrotate.j2 file is a shell script template designed to configure log rotation specifically for environments running inside Docker or containerized setups. Its primary function is to ensure that log files stored in a designated directory (/logsdir) are rotated regularly based on size and quantity parameters. This prevents excessive disk space usage by logs and maintains system performance.

The script performs environment checks to verify it runs inside a Docker container, sets up log rotation configuration files for logrotate, adjusts relevant file permissions, and schedules periodic execution of log rotation and permissions fixes using crond.


Detailed Explanation of Script Components

Docker Environment Check

if [[ -f /.dockerenv ]] || grep -Eq '(lxc|docker)' /proc/1/cgroup; then
    echo -n
else
    echo "Docker only!"
    exit 1
fi

Logrotate Configuration Setup

rm /etc/logrotate.d/*
cat >/etc/logrotate.d/node <<EOF
/logsdir/*.log {
    missingok
    rotate {{ LOG_ROTATE_AMOUNT }}
    size {{ LOG_ROTATE_SIZE }}
    notifempty
    copytruncate
}
EOF

Permissions Management

chown 0:0 /etc/logrotate.d
chown 0:0 /etc/logrotate.d/node

chmod 755 /etc/logrotate.d
chmod 644 /etc/logrotate.d/node

chmod 755 /logsdir

Cron Jobs Setup

echo "59 * * * * /bin/chmod 755 /logsdir" > /etc/crontabs/root
echo "0 * * * * /usr/sbin/logrotate -v /etc/logrotate.conf" >> /etc/crontabs/root

Starting Cron Daemon

echo "Starting crond"
crond -f

Interaction with Other System Components


Visual Diagram

flowchart TD
A[Start Script] --> B{Check Docker Env}
B -- Yes --> C[Remove Existing /etc/logrotate.d/*]
B -- No --> D[Print "Docker only!" & Exit]
C --> E[Write /etc/logrotate.d/node config]
E --> F[Set Ownership & Permissions]
F --> G[Write Cron Jobs to /etc/crontabs/root]
G --> H[Start crond in Foreground]
style B fill:#f9f,stroke:#333,stroke-width:2px
style D fill:#faa,stroke:#333,stroke-width:2px
style H fill:#bbf,stroke:#333,stroke-width:2px

Usage Notes


For further detail on logrotate options and cron scheduling, refer to Logrotate Configuration and Cron Scheduling. For container environment detection specifics, see Docker Environment Detection.