Categories
SysOps

How to use tmpfs for temporary directory

How to use tmpfs for temporary directory (/tmp).

Inspect Temporary Directory (/tmp) systemd mount.

$ cat  /usr/share/systemd/tmp.mount 
#  SPDX-License-Identifier: LGPL-2.1-or-later
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Temporary Directory (/tmp)
Documentation=https://systemd.io/TEMPORARY_DIRECTORIES
Documentation=man:file-hierarchy(7)
Documentation=https://www.freedesktop.org/wiki/Software/systemd/APIFileSystems
ConditionPathIsSymbolicLink=!/tmp
DefaultDependencies=no
Conflicts=umount.target
Before=local-fs.target umount.target
After=swap.target

[Mount]
What=tmpfs
Where=/tmp
Type=tmpfs
Options=mode=1777,strictatime,nosuid,nodev,size=50%,nr_inodes=400k

[Install]
WantedBy=local-fs.target

Copy tmp.mount to run-time unit definition location.

$ sudo cp  /usr/share/systemd/tmp.mount /etc/systemd/system/

Reload systemd configuration.

$ sudo systemctl daemon-reload

Check tmp mount status.

$ sudo systemctl status tmp.mount 
● tmp.mount - Temporary Directory (/tmp)
     Loaded: loaded (/etc/systemd/system/tmp.mount; disabled; vendor preset: enabled)
     Active: inactive (dead)
      Where: /tmp
       What: tmpfs
       Docs: https://systemd.io/TEMPORARY_DIRECTORIES
             man:file-hierarchy(7)
             https://www.freedesktop.org/wiki/Software/systemd/APIFileSystems

Enable tmp mount, but not now as it can break running applications.

$ sudo systemctl enable tmp.mount 
Created symlink /etc/systemd/system/local-fs.target.wants/tmp.mount → /etc/systemd/system/tmp.mount.

Reboot system.

$ sudo reboot

Inspect tmp mount status.

$ sudo systemctl status tmp.mount 
● tmp.mount - Temporary Directory (/tmp)
     Loaded: loaded (/etc/systemd/system/tmp.mount; enabled; vendor preset: enabled)
     Active: active (mounted) since Tue 2021-06-22 07:12:27 UTC; 1min 13s ago
      Where: /tmp
       What: tmpfs
       Docs: https://systemd.io/TEMPORARY_DIRECTORIES
             man:file-hierarchy(7)
             https://www.freedesktop.org/wiki/Software/systemd/APIFileSystems
      Tasks: 0 (limit: 1123)
     Memory: 4.0K
        CPU: 2ms
     CGroup: /system.slice/tmp.mount

Warning: journal has been rotated since unit was started, output may be incomplete.

Check tmp mount size.

$ df -h /tmp/
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           485M     0  485M   0% /tmp

Check tmp mount options.

$ cat /proc/mounts | awk '$2 == "/tmp" {print}'
tmpfs /tmp tmpfs rw,nosuid,nodev,size=496024k,nr_inodes=409600 0 0

Done.