Master Linux Filesystem: Complete Guide to Directory Structure for Sysadmins
This comprehensive tutorial walks you through the Linux filesystem hierarchy, explaining the purpose of each core directory, best practices for management, real-world examples, and advanced operational tips such as permission hardening, monitoring, backup strategies, and performance optimization for reliable system administration.
Linux系统目录结构完全解析:从入门到精通的进阶之路
Ever felt lost navigating a Linux system? This article dives deep into the Linux file system core, helping you understand every directory so you can move through Linux like a seasoned driver.
一、为什么理解Linux目录结构如此重要?
In 15 years of operations, many production incidents were caused by unfamiliarity with the directory layout—for example, a colleague accidentally deleted a critical library under /lib, rendering the system unbootable, or wrote log files to /, filling the root partition and causing service crashes.
The Linux directory tree is like a city road system: each path has a specific purpose and rule. Understanding it prevents mistakes and makes operations more efficient.
二、Linux目录结构的设计哲学
2.1 一切皆文件的Unix哲学
Linux inherits the Unix "everything is a file" design. Not only regular files and directories are files; hardware devices, process information, and network connections are abstracted as files, making system management elegant.
Example: view CPU information with: cat /proc/cpuinfo Send data to a serial device:
echo "Hello" > /dev/ttyS02.2 FHS标准:秩序的基石
The Filesystem Hierarchy Standard (FHS) defines the purpose of each directory, ensuring consistency across Linux distributions, much like building codes in construction.
三、核心目录深度剖析
3.1 根目录(/):一切的起点
The root directory is the top of the Linux file system; all other directories branch from here, like the roots of an inverted tree.
实战经验分享: In production, allocate 20‑30 GB for /. Keep it lean; store actual data on separate partitions so the system can still boot if a data partition fails.
# 查看根目录使用情况
df -h /
# 查看根目录下各子目录占用空间
du -sh /*3.2 /bin 和 /sbin:系统命令的家园
/bin stores basic commands available to all users (e.g., ls, cp, mv) required for boot and single‑user mode.
/sbin holds administrator commands (e.g., fdisk, ifconfig) usually unavailable to regular users.
In modern distributions ( CentOS 7+, Ubuntu 16.04+), /bin is a symlink to /usr/bin and /sbin to /usr/sbin, simplifying the layout while preserving traditional meanings.
# 查看符号链接关系
ls -ld /bin /sbin
# 统计 /usr/bin 下的命令数量
ls /usr/bin | wc -l3.3 /etc:配置文件的中枢
/etccontains almost all system configuration files. Mastering this directory gives you control over the Linux system.
/etc/systemd/ :systemd service configuration
/etc/nginx/ :Nginx configuration
/etc/ssh/ :SSH service configuration
/etc/cron.d/ :Scheduled task configuration
/etc/sysconfig/ :Red Hat‑style service configuration
Typical network configuration examples:
# CentOS/RHEL network configuration
vi /etc/sysconfig/network-scripts/ifcfg-eth0
# Ubuntu (new version) network configuration
vi /etc/netplan/01-netcfg.yaml
# Common DNS configuration
vi /etc/resolv.conf3.4 /home:用户的私人领地
Each normal user has a directory under /home for personal files, configurations, and desktop settings.
目录权限管理:
# 创建新用户时自动创建 home 目录
useradd -m newuser
# 设置正确的权限(很重要!)
chmod 700 /home/newuser
chown -R newuser:newuser /home/newuser
# 限制用户磁盘配额
quotactl -u newuser -l 10G /home3.5 /root:超级管理员的专属空间
/rootis the home directory of the root user, placed directly under / for security. It typically stores admin scripts and root’s configuration files.
安全建议:
# 限制 /root 目录访问权限
chmod 700 /root
# 定期清理 root 目录下的历史命令
echo "HISTSIZE=1000" >> /root/.bashrc
echo "HISTFILESIZE=2000" >> /root/.bashrc3.6 /usr:Unix系统资源的宝库
/usris one of the largest directories, containing most programs and files.
关键子目录:
/usr/bin/ :用户命令
/usr/sbin/ :系统管理命令
/usr/lib/ :库文件
/usr/local/ :本地编译安装的软件默认位置
/usr/share/ :架构无关的共享数据
Standard compile‑install workflow:
# 下载源码
wget https://example.com/software.tar.gz
tar -xzf software.tar.gz
cd software/
# 配置、编译、安装
./configure --prefix=/usr/local/software
make -j$(nproc)
make install
# 添加到 PATH
echo 'export PATH=/usr/local/software/bin:$PATH' >> /etc/profile
source /etc/profile3.7 /var:动态数据的聚集地
/varstores frequently changing files such as logs, caches, and mail queues—an ops engineer’s most common directory.
重要子目录详解:
/var/log/: 日志文件中心
# 查看系统日志
tail -f /var/log/messages # CentOS/RHEL
tail -f /var/log/syslog # Ubuntu/Debian
# 日志轮转配置
vi /etc/logrotate.d/custom-app/var/lib/: 程序数据存储
# MySQL 数据目录
ls /var/lib/mysql/
# Docker 镜像和容器
ls /var/lib/docker//var/cache/: 缓存目录
# 清理 yum 缓存
yum clean all
# 清理 apt 缓存
apt-get clean3.8 /tmp:临时文件的中转站
/tmpholds temporary files and is cleared on reboot. Any user can write here, which introduces security risks.
安全加固措施:
# 为 /tmp 设置独立分区并启用安全选项
mount -o remount,noexec,nosuid,nodev /tmp
# 永久写入 /etc/fstab
echo "tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0" >> /etc/fstab
# 定期清理临时文件
find /tmp -type f -atime +7 -delete3.9 /dev:设备文件的集合
/devcontains all device files. In Linux, hardware devices are abstracted as files, accessed via read/write operations.
Common device files:
/dev/null – discards all writes
/dev/zero – provides infinite zero bytes
/dev/random – random number generator
/dev/tty* – terminal devices
# 快速创建大文件
dd if=/dev/zero of=bigfile bs=1G count=10
# 安全删除文件
shred -vfz -n 3 sensitive_file3.10 /proc 和 /sys:内核的窗口
These virtual filesystems provide runtime kernel and process information without consuming disk space.
/proc: 进程和系统信息
# 查看 CPU 信息
cat /proc/cpuinfo
# 查看内存信息
cat /proc/meminfo
# 查看某进程详细信息
cat /proc/1234/status
# 实时监控中断
watch -n 1 cat /proc/interrupts/sys: 内核参数调整
# 启用 IP 转发
echo 1 > /proc/sys/net/ipv4/ip_forward
# 永久修改内核参数
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p
# 查看块设备队列深度
cat /sys/block/sda/queue/nr_requests3.11 /opt:第三方软件的家
/optis used for optional third‑party packages, keeping them isolated from system software.
# 安装示例
tar -xzf software.tar.gz -C /opt/
ln -s /opt/software/bin/app /usr/local/bin/app
# 环境变量配置
echo 'export PATH=/opt/software/bin:$PATH' >> /etc/profile.d/software.sh3.12 /mnt 和 /media:挂载点
These directories serve as temporary mount points. /mnt is for manual mounts; /media is used by the system for auto‑mounted removable media.
# 挂载 ISO 文件
mount -o loop ubuntu.iso /mnt/iso
# 挂载 NFS
mount -t nfs 192.168.1.100:/share /mnt/nfs
# 挂载 Windows 共享
mount -t cifs //192.168.1.100/share /mnt/smb -o username=user四、高级运维技巧与最佳实践
4.1 目录权限管理的艺术
Correct permission settings are the first line of defense for system security.
# 关键目录权限检查脚本
cat > /usr/local/bin/check_permissions.sh <<'EOF'
#!/bin/bash
echo "Checking critical directory permissions..."
dirs=(
"/etc:755"
"/boot:755"
"/root:700"
"/var/log:755"
"/tmp:1777"
)
for item in "${dirs[@]}"; do
dir="${item%:*}"
expected="${item#*:}"
actual=$(stat -c %a "$dir")
if [ "$actual" != "$expected" ]; then
echo "WARNING: $dir has permission $actual, expected $expected"
else
echo "OK: $dir permission is correct"
fi
done
EOF
chmod +x /usr/local/bin/check_permissions.sh4.2 磁盘空间监控与预警
# 磁盘使用率监控脚本
cat > /usr/local/bin/disk_monitor.sh <<'EOF'
#!/bin/bash
THRESHOLD=80
ALERT_EMAIL="[email protected]"
df -H | grep -vE '^Filesystem|tmpfs|cdrom|udev' | awk '{print $5 " " $1}' | while read output; do
usage=$(echo $output | awk '{print $1}' | cut -d% -f1)
partition=$(echo $output | awk '{print $2}')
if [ $usage -ge $THRESHOLD ]; then
echo "Warning: Partition $partition is ${usage}% full" | \
mail -s "Disk Alert: $(hostname)" $ALERT_EMAIL
fi
done
EOF
chmod +x /usr/local/bin/disk_monitor.sh
# 每小时检查一次
echo "0 * * * * /usr/local/bin/disk_monitor.sh" | crontab -4.3 目录结构备份策略
# 系统配置备份脚本
cat > /usr/local/bin/backup_configs.sh <<'EOF'
#!/bin/bash
BACKUP_DIR="/backup/configs/$(date +%Y%m%d)"
mkdir -p $BACKUP_DIR
# 备份重要配置目录
tar -czf $BACKUP_DIR/etc.tar.gz /etc
tar -czf $BACKUP_DIR/root.tar.gz /root
tar -czf $BACKUP_DIR/usr_local.tar.gz /usr/local
# 记录已安装软件列表(RHEL/CentOS)
rpm -qa > $BACKUP_DIR/rpm_packages.list
# Debian/Ubuntu: dpkg -l > $BACKUP_DIR/dpkg_packages.list
# 备份 crontab
crontab -l > $BACKUP_DIR/crontab.backup
# 删除 30 天前的备份
find /backup/configs -type d -mtime +30 -exec rm -rf {} \;
echo "Backup completed: $BACKUP_DIR"
EOF
chmod +x /usr/local/bin/backup_configs.sh4.4 性能优化:合理规划目录结构
分区策略建议: For production servers, a typical partition scheme includes separate partitions for /, /boot, /var, /var/log, /home, /opt, and a data partition.
/ 20‑30GB (system root)
/boot 1‑2GB (boot partition)
/var 50‑100GB (logs and variable data)
/var/log 20‑50GB (dedicated log partition)
/home <em>as needed</em>
/opt <em>as needed</em>
/data <em>remaining space</em>
swap 1‑2× RAM使用 LVM 的优势:
# 创建 LVM 卷组
vgcreate vg_data /dev/sdb
# 创建逻辑卷
lvcreate -L 100G -n lv_var vg_data
lvcreate -L 50G -n lv_varlog vg_data
# 格式化并挂载
mkfs.xfs /dev/vg_data/lv_var
mount /dev/vg_data/lv_var /var
# 动态扩容示例
lvextend -L +20G /dev/vg_data/lv_var
xfs_growfs /var # XFS
# 或者 resize2fs /dev/vg_data/lv_var # ext4五、常见问题与故障排查
5.1 根目录空间不足
症状: 系统响应缓慢,无法创建新文件,服务启动失败。
排查步骤:
# 查找大文件
find / -type f -size +1G 2>/dev/null
# 查找占用空间最大的目录
du -xh / | sort -rh | head -20
# 清理包管理器缓存
yum clean all # RHEL/CentOS
apt-get clean # Ubuntu/Debian
# 清理日志
journalctl --vacuum-time=7d
find /var/log -name "*.gz" -delete
find /var/log -name "*.1" -delete
# 查找已删除但仍被占用的文件
lsof | grep deleted5.2 /tmp 目录权限异常
修复方法:
# 重置 /tmp 权限
chmod 1777 /tmp
chown root:root /tmp
# 如果 /tmp 是独立分区,重新挂载
mount -o remount /tmp5.3 误删除重要目录
预防措施:
# 为 rm、cp、mv 添加交互式别名
echo "alias rm='rm -i'" >> ~/.bashrc
echo "alias cp='cp -i'" >> ~/.bashrc
echo "alias mv='mv -i'" >> ~/.bashrc
# 创建回收站机制
mkdir -p ~/.trash
alias del='mv -t ~/.trash'
# 定期清理回收站(30 天后)
echo "0 0 * * 0 find ~/.trash -mtime +30 -delete" | crontab -六、实战项目:构建标准化运维目录结构
# 创建标准化运维目录结构
cat > /usr/local/bin/init_ops_dirs.sh <<'EOF'
#!/bin/bash
# 创建运维工作目录
mkdir -p /ops/{scripts,logs,backup,config,docs,tools}
# 脚本子目录
mkdir -p /ops/scripts/{daily,weekly,monthly,emergency}
# 日志子目录
mkdir -p /ops/logs/{system,application,security,audit}
# 备份子目录
mkdir -p /ops/backup/{daily,weekly,monthly,config}
# 配置子目录
mkdir -p /ops/config/{templates,production,staging}
# 文档子目录
mkdir -p /ops/docs/{runbook,architecture,sop,troubleshooting}
# 工具子目录
mkdir -p /ops/tools/{monitoring,deployment,security}
# 设置权限
chown -R root:ops /ops
chmod -R 750 /ops
chmod -R 770 /ops/logs
# 创建说明文件
cat > /ops/README.md <<'DOC'
# 运维目录结构说明
## /ops/scripts
- daily: 每日执行的脚本
- weekly: 每周执行的脚本
- monthly: 每月执行的脚本
- emergency: 紧急情况使用的脚本
## /ops/logs
- system: 系统相关日志
- application: 应用程序日志
- security: 安全相关日志
- audit: 审计日志
## /ops/backup
- daily: 每日备份
- weekly: 每周备份
- monthly: 每月备份
- config: 配置文件备份
## /ops/config
- templates: 配置模板
- production: 生产环境配置
- staging: 测试环境配置
## /ops/docs
- runbook: 运行手册
- architecture: 架构文档
- sop: 标准操作流程
- troubleshooting: 故障排查指南
## /ops/tools
- monitoring: 监控工具
- deployment: 部署工具
- security: 安全工具
DOC
echo "运维目录结构初始化完成!"
ls -la /ops/
EOF
chmod +x /usr/local/bin/init_ops_dirs.sh
/usr/local/bin/init_ops_dirs.sh七、性能调优:基于目录结构的优化策略
7.1 I/O 性能优化
# 将高 I/O 目录放在 SSD 上(假设 /dev/nvme0n1p1 为 SSD)
mkfs.xfs /dev/nvme0n1p1
mount /dev/nvme0n1p1 /var/lib/mysql
# 设置文件系统参数
mount -o noatime,nodiratime /dev/nvme0n1p1 /var/lib/mysql
# 调整预读参数
blockdev --setra 256 /dev/nvme0n17.2 内存文件系统优化
# 将频繁访问的小文件放入内存
mount -t tmpfs -o size=2G tmpfs /var/cache/nginx
# 永久配置到 /etc/fstab
echo "tmpfs /var/cache/nginx tmpfs size=2G,mode=755 0 0" >> /etc/fstab八、安全加固:目录权限最佳实践
# 安全审计脚本
cat > /usr/local/bin/security_audit.sh <<'EOF'
#!/bin/bash
echo "=== Linux目录安全审计 ==="
echo "检查时间: $(date)"
echo "========================="
# 检查 SUID/SGID 文件
echo -e "
[*] 检查SUID/SGID文件..."
find / -type f \( -perm -4000 -o -perm -2000 \) -exec ls -la {} \; 2>/dev/null
# 检查全局可写目录
echo -e "
[*] 检查全局可写目录..."
find / -type d -perm -002 2>/dev/null | grep -v "/proc\|/sys\|/dev/shm"
# 检查无主文件
echo -e "
[*] 检查无主文件..."
find / -nouser -o -nogroup 2>/dev/null | grep -v "/proc\|/sys"
# 检查隐藏文件
echo -e "
[*] 检查可疑隐藏文件..."
find / -name ".*" -type f 2>/dev/null | grep -v "/home\|/root" | head -20
echo -e "
审计完成!"
EOF
chmod +x /usr/local/bin/security_audit.sh九、容器化时代的目录管理
With Docker and Kubernetes, understanding container directory structures is equally important.
# Docker volume mount best practice
docker run -d \
-v /data/mysql:/var/lib/mysql \
-v /data/logs/mysql:/var/log/mysql \
-v /etc/mysql/conf.d:/etc/mysql/conf.d:ro \
--name mysql \
mysql:8.0
# Kubernetes PersistentVolume example
cat > pv-example.yaml <<'EOF'
apiVersion: v1
kind: PersistentVolume
metadata:
name: app-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/data/k8s/volumes/app"
EOF十、总结与进阶建议
Mastering the Linux directory structure is the foundation for becoming an excellent operations engineer. After reading this article you should now understand:
每个目录的用途和重要性 – know where files belong.
目录管理的最佳实践 – how to plan and maintain the hierarchy.
常见问题的解决方案 – troubleshooting steps.
安全和性能优化技巧 – keep the system safe and efficient.
进阶学习路径:
深入学习文件系统(ext4、XFS、Btrfs 等)
掌握 LVM 和 RAID 高级存储管理技术
了解容器存储驱动(overlay2、devicemapper 等)
学习分布式存储系统(Ceph、GlusterFS)
实践建议:
在虚拟机中反复练习本文提到的命令
尝试从零开始搭建一个生产级别的服务器
参与开源项目,观察优秀项目的目录组织方式
建立自己的运维工具库和脚本集
Remember, theoretical knowledge is only the beginning; real mastery comes from continuous practice, fault isolation, and system optimization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Community
A leading IT operations community where professionals share and grow together.
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.
