Optimizing Your Raspberry Pi: Tips to Protect Your SD Card and Enhance Performance

Optimizing Your Raspberry Pi: Tips to Protect Your SD Card and Enhance Performance

Ultimate Raspberry Pi Optimization Guide: Extend SD Card Life & Boost Security

In this article, I'll provide an overview of various Raspberry Pi optimization techniques to protect your Raspberry Pi SD card, extend its lifespan, and ensure that security updates are installed automatically.These tips and tricks are suitable for any Linux operating system.

Useful techniques

1- Write temporary logs to RAM

2- Write useful logs to RAM and sync them periodically

3- Rotate logs to save disk space

4- Disable swap

5- keep the OS patched and up-to-date automatically

Write temporary logs to RAM

To extend the life of your SD card and improve speed, it's crucial to reduce the number of write operations to it. This can be achieved by writing temporary logs to RAM instead of the SD card.

Linux systems write temporary logs to specific locations, which are usually removed upon system reboot. By mounting these locations as tmpfs (temporary file systems) in RAM, you can minimize the wear on your SD card.

You can add the following to the /etc/fstab:

tmpfs    /tmp    tmpfs    defaults,noatime,nosuid,size=100m    0 0
tmpfs    /var/run    tmpfs 	  defaults,noatime,nosuid,size=30m    0 0
tmpfs    /var/cache/apt    tmpfs    defaults,noatime,nosuid,size=400m    0 0

This will make sure the following locations are mounted as tmpfs after the system reboot:

  • /tmp: Used for temporary files by programs and the operating system.
  • /var/run: Stores runtime files and process-related information.
  • /var/cache/apt: Used by the APT package manager to store cached package files and metadata.

Please make sure to adjust the size of these directories based on your requirements.

💡
You can mount them manually without reboot but it's not recommended as you will have to restart the services so they can write to the locations again.

Write Useful Logs to RAM and Sync Them Periodically Using Log2Ram

Log2ram is a useful tool designed to mitigate the wear and tear on storage media like SD cards caused by excessive logging activity. This tool is especially beneficial for Raspberry Pi devices with limited storage.

To install Log2ram, add the key and source list to the Raspberry Pi repositories, then use apt to install it. Log2ram can be configured to adjust directory sizes, disable emails, and use rsync to sync logs from RAM to the SD card periodically. This reduces the constant write operations to the SD card, significantly improving its lifespan.

You can execute the following commands:

sudo wget -O /usr/share/keyrings/azlux-archive-keyring.gpg  https://azlux.fr/repo.gpg
echo "deb [signed-by=/usr/share/keyrings/azlux-archive-keyring.gpg] http://packages.azlux.fr/debian/ bullseye main" | sudo tee -a /etc/apt/sources.list.d/azlux.list
sudo apt update
sudo apt install -y log2ram rsync

Few settings can be modified like changing the directory size, disable the emails and use rsync to sync logs from the RAM to the SD card.

This will sync the logs every specific amount of time instead of writing the logs to the SD card all the time improving the lifespan.

The config file is located at /etc/log2ram.conf . The config file will have explanation of all possible settings. For me, i use the following configurations:

# Configuration file for Log2Ram (https://github.com/azlux/log2ram) under MIT license.
# This configuration file is read by the log2ram service

# Size for the ram folder, it defines the size the log folder will reserve into the RAM.
# If it's not enough, log2ram will not be able to use ram. Check you /var/log size folder.
# The default is 40M and is basically enough for a lot of applications.
# You will need to increase it if you have a server and a lot of log for example.
SIZE=200M

# If there are some errors with available RAM space, a system mail will be send
# Change it to false and you will have only a log if there is no place on RAM anymore.
MAIL=false

# Variable for folders to put in RAM. You need to specify the real folder `/path/folder` , the `/path/hdd.folder` will be automatically created. Multiple path can be separeted by `;`. Do not add the final `/` !
# example : PATH_DISK="/var/log;/home/test/FolderInRam"
PATH_DISK="/var/log"

# **************** Zram backing conf  *************************************************

# ZL2R Zram Log 2 Ram enables a zram drive when ZL2R=true ZL2R=false is mem only tmpfs
ZL2R=false
# COMP_ALG this is any compression algorithm listed in /proc/crypto
# lz4 is fastest with lightest load but deflate (zlib) and Zstandard (zstd) give far better compression ratios
# lzo is very close to lz4 and may with some binaries have better optimisation
# COMP_ALG=lz4 for speed or Zstd for compression, lzo or zlib if optimisation or availabilty is a problem
COMP_ALG=lz4
# LOG_DISK_SIZE is the uncompressed disk size. Note zram uses about 0.1% of the size of the disk when not in use
# LOG_DISK_SIZE is expected compression ratio of alg chosen multiplied by log SIZE
# lzo/lz4=2.1:1 compression ratio zlib=2.7:1 zstandard=2.9:1
# Really a guestimate of a bit bigger than compression ratio whilst minimising 0.1% mem usage of disk size
LOG_DISK_SIZE=400M

USE_RSYNC=true

In this way, the logs are saved to RAM then copied to the SD card frequently reducing the write operations.

Rotate logs using logrotate

Log rotation involves periodically compressing and archiving log files to manage their size and prevent them from growing indefinitely. This helps in maintaining a healthy system and saves disk space.

You can install logrotate using:

sudo apt install logrotate

The main config file is located at /etc/logrotate.conf and I use the following:

# see "man logrotate" for details
# global options do not affect preceding include directives
# rotate log files weekly
weekly
# keep 4 weeks worth of backlogs
rotate 2
# create new (empty) log files after rotating old ones
create
# use date as a suffix of the rotated file
#dateext
# uncomment this if you want your log files compressed
compress
# packages drop log rotation information into this directory
include /etc/logrotate.d
# system-specific logs may also be configured here.

As you see , I have enabled the compress option to make sure the rotated logs are compressed and changed the rotate value to be 2 instead of 4.

You can also create a config file to rotate specific logs by adding it to the /etc/logrotate.d/ directory.

Taking an example, if you want to rotate the Apache access logs located at /var/log/httpd/ you can create a config file called /etc/logrotate.d/httpd with the following content:

/var/log/httpd/*.log {
    daily
    rotate 30
    compress
    missingok
    notifempty
}

After modifying the configurations, you have to restart the logrotate service for the change to take effect using:

sudo service logrotate restart

Using logrotate will ensure that your SD card will not be filled quickly.

Disable SWAP

SD cards have a limited number of write cycles before they start to degrade. Each write operation to the swap space consumes a portion of the SD card's write endurance. By disabling swap, especially on a Raspberry Pi with ample memory (like the Raspberry Pi 4 with 8 GB RAM), you can significantly extend the lifespan of your SD card.

To disable swap, use the following command:

sudo dphys-swapfile swapoff
sudo dphys-swapfile uninstall
sudo apt purge -y dphys-swapfile

Get Automatic Security Updates Using Unattended-Upgrades

One of the primary goals of unattended upgrades is to ensure that security updates are promptly applied to your system, reducing vulnerabilities to known security threats.

This can be installed using:

sudo apt install unattended-upgrades

Next step is to modify the configuration to support raspberry pi.

To enable the auto update, edit the following config file /etc/apt/apt.conf.d/20auto-upgrades to be like:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

The first option will automatically update the list of packages to ensure that the system has the latest information about available software packages.

The second option will updates to the packages without requiring manual intervention. This includes security patches, bug fixes, and other updates provided by the package repositories.

Finally, configure from where the unattended upgrade will pull the packages in the /etc/apt/apt.conf.d/50unattended-upgrades config file:

Unattended-Upgrade::Origins-Pattern {
        "origin=Debian,codename=${distro_codename},label=Debian"; 
        "origin=Debian,codename=${distro_codename},label=Debian-Security"; 
        "origin=Debian,codename=${distro_codename}-security,label=Debian-Security";
        "origin=Raspbian,codename=${distro_codename},label=Raspbian";
        "origin=Raspberry Pi Foundation,codename=${distro_codename},label=Raspberry Pi Foundation"; 
};

// Python regular expressions, matching packages to exclude from upgrading
Unattended-Upgrade::Package-Blacklist {
};

// Automatically reboot *WITHOUT CONFIRMATION* if
//  the file /var/run/reboot-required is found after the upgrade
Unattended-Upgrade::Automatic-Reboot "true";

// If automatic reboot is enabled and needed, reboot at the specific
// time instead of immediately
//  Default: "now"
Unattended-Upgrade::Automatic-Reboot-Time "03:00";

As you see I have enabled the automatic reboot at 3 am so the raspberry pi will reboot automatically if needed.

Professional Page

Conclusion

By implementing these Raspberry Pi optimization techniques, you can protect your SD card, enhance performance, and ensure that your system remains secure and up-to-date. Whether you're using your Raspberry Pi as a media center, for retro games, or as a development platform, these tips will help you get the most out of your device.

Remember to use a reliable power supply and quality peripherals, like a high-quality microSD card and external storage, to further improve the overall performance and longevity of your Raspberry Pi setup. Happy tinkering!

buy me a coffe