Linux_Practical_Interview_1001 1250
Linux Practical Interview Questions (1001-1250)
Section titled “Linux Practical Interview Questions (1001-1250)”Linux System Architecture
Section titled “Linux System Architecture”Q1001: How do Linux kernel and user space interact?
Section titled “Q1001: How do Linux kernel and user space interact?”Answer: The Linux kernel and user space interact through system calls, which are the primary interface between user applications and the kernel.
# System call interface# User space -> libc -> system call wrapper -> kernel# Example: read() system callssize_t read(int fd, void *buf, size_t count);
# View system callsstrace -e trace=read,write cat /etc/passwd
# List system callsman syscalls# orcat /usr/include/asm/unistd_64.h | head -30Q1002: What is the role of the init system in Linux?
Section titled “Q1002: What is the role of the init system in Linux?”Answer: The init system is the first process started by the kernel (PID 1) and is responsible for:
- Starting system services in the correct order
- Managing runlevels/targets
- Handling system shutdown and restart
- Being the parent of all orphaned processes
# Systemd (modern)systemctl statussystemctl list-units --type=service
# SysVinit (legacy)runlevells -la /etc/rc.d/
# Runitsv status /service/*Q1003: How does Linux handle process scheduling?
Section titled “Q1003: How does Linux handle process scheduling?”Answer: Linux uses Completely Fair Scheduler (CFS) which provides fair CPU time distribution:
# View process priority and nice valueps -eo pid,ni,pri,pcpu,commrenice 10 -p 1234
# Set real-time prioritychrt -f 50 -p 1234chrt -r -p 50 1234
# View schedulercat /proc/1234/schedQ1004: Explain Linux virtual memory management.
Section titled “Q1004: Explain Linux virtual memory management.”Answer: Linux uses demand paging with virtual memory:
# View memory infocat /proc/meminfofree -hvmstat 1
# View process memory mapspmap -x 1234cat /proc/1234/maps
# Memory zonescat /proc/buddyinfoQ1005: What are Linux namespaces and how are they used?
Section titled “Q1005: What are Linux namespaces and how are they used?”Answer: Namespaces provide process isolation:
# View namespacesls -la /proc/$$/ns/
# Create a new namespace (user namespace requires kernel 3.8+)unshare --mount --pid --fork --user --map-root-user bash
# Network namespaceip netns add mynetip netns exec mynet ip link listLinux Boot Process
Section titled “Linux Boot Process”Q1006: Describe the Linux boot process from power on.
Section titled “Q1006: Describe the Linux boot process from power on.”Answer:
- BIOS/UEFI POST
- Boot loader (GRUB2) loads kernel
- Kernel initializes and loads initrd/initramfs
- Kernel mounts root filesystem
- Init system (systemd) starts
- Runlevel targets reached
# View boot messagesdmesg | lessjournalctl -b
# Boot time analysissystemd-analyze timesystemd-analyze blame | head -20Q1007: How do you troubleshoot boot issues in Linux?
Section titled “Q1007: How do you troubleshoot boot issues in Linux?”Answer:
# Check boot logsjournalctl -b -1 # Previous bootjournalctl -b --priority=err
# Emergency mode# At GRUB menu, add 'systemd.unit=emergency.target'
# Recovery mode# At GRUB menu, add 'systemd.unit=rescue.target'
# Check filesystemfsck /dev/sda1mount -o remount,rw /Q1008: What is GRUB2 and how do you configure it?
Section titled “Q1008: What is GRUB2 and how do you configure it?”Answer: GRUB2 (Grand Unified Boot Loader) is the default boot loader:
# Edit GRUB configvim /etc/default/grub
# Common settingsGRUB_TIMEOUT=5GRUB_DEFAULT=savedGRUB_CMDLINE_LINUX="quiet splash"
# Regenerate configupdate-grub # Debian/Ubuntugrub2-mkconfig -o /boot/grub2/grub.cfg # RHEL/CentOS
# GRUB command line# Press 'e' at boot menu to editQ1009: What is initramfs and its purpose?
Section titled “Q1009: What is initramfs and its purpose?”Answer: Initial RAM filesystem contains modules needed before root filesystem is mounted:
# Rebuild initramfsdracut -f # RHEL/CentOSupdate-initramfs -u # Debian/Ubuntu
# View contentslsinitramfs /boot/initrd.img-$(uname -r)zcat /boot/initrd.img | cpio -id
# Custom initramfs# Add to /etc/initramfs-tools/modulesQ1010: How does systemd replace SysVinit?
Section titled “Q1010: How does systemd replace SysVinit?”Answer: Systemd uses unit files instead of init scripts:
# Service unit example[Unit]Description=My ServiceAfter=network.target
[Service]Type=simpleExecStart=/usr/bin/myserviceRestart=on-failure
[Install]WantedBy=multi-user.target
# Manage servicesystemctl enable myservicesystemctl start myservicesystemctl status myserviceLinux File System
Section titled “Linux File System”Q1011: How do you create and manage LVM?
Section titled “Q1011: How do you create and manage LVM?”Answer: Logical Volume Manager provides flexible storage:
# Physical volumepvcreate /dev/sdb1pvdisplaypvscan
# Volume groupvgcreate vg_data /dev/sdb1vgdisplayvgextend vg_data /dev/sdc1
# Logical volumelvcreate -L 10G -n lv_mydata vg_datalvcreate -l 100%FREE -n lv_backup vg_data
# Format and mountmkfs.xfs /dev/vg_data/lv_mydatamount /dev/vg_data/lv_mydata /mnt/data
# Resizelvextend -L +5G /dev/vg_data/lv_mydataresize2fs /dev/vg_data/lv_mydataQ1012: What is the difference between ext4 and XFS?
Section titled “Q1012: What is the difference between ext4 and XFS?”Answer:
| Feature | ext4 | XFS |
|---|---|---|
| Max file size | 16TB | 8EB |
| Max volume | 1EB | 8EB |
| Journaling | Yes | Yes |
| Online resize | Limited | Yes |
| Performance | Small files | Large files |
# Create ext4mkfs.ext4 -j /dev/sdb1
# Create XFSmkfs.xfs -f /dev/sdb1
# Tune ext4tune2fs -o journal_data /dev/sda1tune2fs -O dir_index /dev/sda1Q1013: How do you manage disk quotas?
Section titled “Q1013: How do you manage disk quotas?”Answer:
# Enable quota/dev/sda1 /home ext4 usrquota,grpquota 0 2
# Initialize quotaquotacheck -cug /homequotaon /home
# Set quotasedquota -u username# orsetquota -u username 10000 15000 1000 2000 /home
# Check quotaquota -u usernamerepquota -aQ1014: What is RAID and how do you configure it in Linux?
Section titled “Q1014: What is RAID and how do you configure it in Linux?”Answer: Redundant Array of Independent Disks:
# Software RAID with mdadmmdadm --create /dev/md0 --level=5 --raid-devices=3 /dev/sdb1 /dev/sdc1 /dev/sdd1
# Manage RAIDmdadm --detail /dev/md0cat /proc/mdstat
# Add sparemdadm /dev/md0 --add /dev/sde1
# Monitormdadm --monitor --mail=admin@example.com --daemonize /dev/md0Q1015: How do you troubleshoot filesystem errors?
Section titled “Q1015: How do you troubleshoot filesystem errors?”Answer:
# Check filesystemfsck -n /dev/sda1 # dry runfsck -y /dev/sda1 # auto repair
# XFS specificxfs_repair /dev/sda1xfs_info /dev/sda1
# View inode usagedf -itune2fs -l /dev/sda1 | grep -i inode
# Recover deleted files (ext3/4)extundelete /dev/sda1 --inode 2Linux Networking
Section titled “Linux Networking”Q1016: How do you configure network bonding?
Section titled “Q1016: How do you configure network bonding?”Answer: Combine multiple NICs for redundancy/performance:
# Load bonding modulemodprobe bonding mode=active-backup
# Create bond interfacecat > /etc/sysconfig/network-scripts/ifcfg-bond0 << EOFDEVICE=bond0TYPE=BondIPADDR=192.168.1.10NETMASK=255.255.255.0ONBOOT=yesBONDING_OPTS="mode=active-backup miimon=100"EOF
# Add slave interfacesecho "MASTER=bond0" >> /etc/sysconfig/network-scripts/ifcfg-eth0echo "MASTER=bond0" >> /etc/sysconfig/network-scripts/ifcfg-eth1
# View bond statuscat /proc/net/bonding/bond0Q1017: How do you configure VLANs in Linux?
Section titled “Q1017: How do you configure VLANs in Linux?”Answer:
# Enable 8021q modulemodprobe 8021q
# Create VLAN interfaceip link add link eth0 name eth0.100 type vlan id 100ip addr add 192.168.100.1/24 dev eth0.100ip link set eth0.100 up
# Or using vconfigvconfig add eth0 100ifconfig eth0.100 192.168.100.1 netmask 255.255.255.0 up
# Persistent VLAN config (RHEL)# /etc/sysconfig/network-scripts/ifcfg-eth0.100Q1018: What is iptables and how do you configure basic rules?
Section titled “Q1018: What is iptables and how do you configure basic rules?”Answer:
# List rulesiptables -L -n -viptables -t nat -L -n -v
# Basic rulesiptables -A INPUT -p tcp --dport 22 -j ACCEPTiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -j DROP
# NAT rulesiptables -t nat -A POSTROUTING -o eth0 -j MASQUERADEiptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
# Save rulesiptables-save > /etc/iptables/rules.v4# orservice iptables saveQ1019: How do you configure network bridging?
Section titled “Q1019: How do you configure network bridging?”Answer:
# Create bridgebrctl addbr br0ip addr add 192.168.1.1/24 dev br0ip link set br0 up
# Add interfacesbrctl addif br0 eth0brctl addif br0 eth1
# View bridgebrctl showip link show type bridge
# Delete bridgeip link set br0 downbrctl delbr br0Q1020: How do you troubleshoot network connectivity issues?
Section titled “Q1020: How do you troubleshoot network connectivity issues?”Answer:
# Check interface statusip link showip addr showethtool eth0
# Test connectivityping -c 4 8.8.8.8traceroute 8.8.8.8mtr 8.8.8.8
# Check DNSdig example.comnslookup example.comcat /etc/resolv.conf
# Check portsnetstat -tulpnss -tulpnlsof -i :80
# Capture packetstcpdump -i eth0 port 80tcpdump -i eth0 host 192.168.1.1Linux Security
Section titled “Linux Security”Q1021: How do you configure SELinux?
Section titled “Q1021: How do you configure SELinux?”Answer: Security-Enhanced Linux provides mandatory access control:
# Check SELinux statusgetenforcesestatus
# Set modesetenforce 1 # Enforcingsetenforce 0 # Permissive
# Configure /etc/selinux/config# SELINUX=enforcing# SELINUXTYPE=targeted
# Manage contextschcon -t httpd_sys_content_t /var/www/html/index.htmlsemanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"restorecon -Rv /web
# Boolean valuesgetsebool -asetsebool -P httpd_can_network_connect onQ1022: How do you configure a firewall with firewalld?
Section titled “Q1022: How do you configure a firewall with firewalld?”Answer:
# Check statusfirewall-cmd --statefirewall-cmd --list-all
# Add servicesfirewall-cmd --permanent --add-service=httpfirewall-cmd --permanent --add-service=https
# Add portsfirewall-cmd --permanent --add-port=8080/tcp
# Zonesfirewall-cmd --permanent --zone=public --add-service=sshfirewall-cmd --set-default-zone=trusted
# Reloadfirewall-cmd --reloadQ1023: How do you secure SSH access?
Section titled “Q1023: How do you secure SSH access?”Answer:
Port 2222PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesMaxAuthTries 3ClientAliveInterval 300AllowUsers user1 user2
# Generate key pairssh-keygen -t ed25519 -C "work laptop"
# Copy keyssh-copy-id user@server
# Fail2banapt install fail2ban# oryum install fail2banQ1024: How do you set up audit logging?
Section titled “Q1024: How do you set up audit logging?”Answer:
# Install auditapt install auditd# oryum install audit
# Configure /etc/audit/auditd.confmax_log_file = 50max_log_file_action = rotate
# Add rulesauditctl -w /etc/passwd -p wa -k passwd_changesauditctl -w /usr/bin/rm -p x -k file_delete
# View logsausearch -k passwd_changesaureport --file
# Make rules persistent# /etc/audit/rules.d/audit.rulesQ1025: How do you implement user authentication with PAM?
Section titled “Q1025: How do you implement user authentication with PAM?”Answer:
# PAM configuration filesls -la /etc/pam.d/
# Example: password policy# /etc/pam.d/common-passwordpassword required pam_pwhistory.so remember=5password [default=1] pam_permit.so
# Limit resources# /etc/security/limits.confusername soft nofile 4096username hard nofile 8192
# Time-based login# /etc/security/time.conflogin;ts001;users;Al0900-1700Linux Containers
Section titled “Linux Containers”Q1026: How do you configure Docker networking?
Section titled “Q1026: How do you configure Docker networking?”Answer:
# List networksdocker network lsdocker network inspect bridge
# Create networkdocker network create --driver bridge mynetworkdocker network create --driver overlay myoverlay
# Connect containerdocker run -d --network mynetwork --name web nginx
# Port mappingdocker run -d -p 8080:80 --name web2 nginx
# DNS resolutiondocker run -d --network-alias db --network mynetwork mysqlQ1027: How do you manage Docker volumes?
Section titled “Q1027: How do you manage Docker volumes?”Answer:
# Create volumedocker volume create mydata
# Mount volumedocker run -v mydata:/data mysql
# Bind mountdocker run -v /host/path:/container/path nginx
# Volume driverdocker volume create --driver local myvolume
# View volumesdocker volume lsdocker volume inspect mydataQ1028: How do you configure Docker Compose?
Section titled “Q1028: How do you configure Docker Compose?”Answer:
version: '3.8'services: web: build: . ports: - "8080:80" environment: - NODE_ENV=production volumes: - ./data:/data depends_on: - db networks: - frontend - backend
db: image: postgres:14 volumes: - db-data:/var/lib/postgresql/data networks: - backend
volumes: db-data:
networks: frontend: backend:Q1029: How do you secure Docker containers?
Section titled “Q1029: How do you secure Docker containers?”Answer:
# Run as non-rootdocker run -u 1000:1000 nginx
# Read-only filesystemdocker run --read-only nginx
# Limit capabilitiesdocker run --cap-drop ALL --cap-add NET_BIND_SERVICE nginx
# Disable networkingdocker run --network none nginx
# Scan imagesdocker scan nginxtrivy image nginx
# Best practices in DockerfileFROM ubuntu:22.04RUN useradd -m appuserUSER appuserQ1030: How do you troubleshoot container issues?
Section titled “Q1030: How do you troubleshoot container issues?”Answer:
# View logsdocker logs container_iddocker logs -f container_iddocker logs --tail 100 container_id
# Inspect containerdocker inspect container_iddocker inspect --format='{{.NetworkSettings.IPAddress}}' container_id
# Execute commandsdocker exec -it container_id /bin/bashdocker exec container_id ps aux
# Resource usagedocker stats container_iddocker stats --no-stream container_id
# Network debuggingdocker run --rm -it --network container:name nicolaka/netshootLinux Performance Tuning
Section titled “Linux Performance Tuning”Q1031: How do you tune CPU performance?
Section titled “Q1031: How do you tune CPU performance?”Answer:
# View CPU infolscpucat /proc/cpuinfo
# CPU frequencycpupower frequency-infocpupower frequency-set -g performance
# CPU affinitytaskset -c 0-3 myapptaskset -p 0xF myapp
# Process prioritynice -n 10 myapprenice 5 -p 1234
# View schedulercat /proc/sched_debugQ1032: How do you tune memory performance?
Section titled “Q1032: How do you tune memory performance?”Answer:
# View memoryfree -hcat /proc/meminfo
# Clear cachesync && echo 3 > /proc/sys/vm/drop_caches
# Swappinesscat /proc/sys/vm/swappinesssysctl vm.swappiness=10# Add to /etc/sysctl.conf# vm.swappiness=10
# Huge pagesecho 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepagesQ1033: How do you tune I/O performance?
Section titled “Q1033: How do you tune I/O performance?”Answer:
# I/O schedulercat /sys/block/sda/queue/schedulerecho cfq > /sys/block/sda/queue/scheduler# orecho deadline > /sys/block/sda/queue/scheduler
# I/O priorityionice -c 2 -n 0 -p 1234
# Block device settingsecho 4096 > /sys/block/sda/queue/read_ahead_kbecho 0 > /sys/block/sda/queue/rotational
# Filesystem optionsmount -o noatime,nodiratime /dev/sda1 /mntQ1034: How do you tune network performance?
Section titled “Q1034: How do you tune network performance?”Answer:
# Network buffer sizessysctl -w net.core.rmem_max=16777216sysctl -w net.core.wmem_max=16777216
# TCP tuningsysctl -w net.ipv4.tcp_window_scaling=1sysctl -w net.ipv4.tcp_congestion_control=cubic
# Make persistent# /etc/sysctl.confnet.core.rmem_max=16777216net.core.wmem_max=16777216
# Ring buffer (NIC)ethtool -G eth0 rx 4096 tx 4096ethtool -g eth0Q1035: How do you use performance monitoring tools?
Section titled “Q1035: How do you use performance monitoring tools?”Answer:
# System performancetophtopatop
# Process monitoringpidstat -p 1234 1prstat -p 1234
# I/O monitoringiostat -xz 1iotop
# Network monitoringnethogsiftopsar -n DEV 1
# Full system analysisperf record -g ./myappperf reportLinux Scripting
Section titled “Linux Scripting”Q1036: How do you write efficient bash scripts?
Section titled “Q1036: How do you write efficient bash scripts?”Answer:
#!/bin/bashset -euo pipefail
# Use functionslog() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"}
# Parse argumentswhile getopts "hvf:" opt; do case $opt in h) help; exit 0 ;; v) VERBOSE=1 ;; f) FILE="$OPTARG" ;; *) exit 1 ;; esacdone
# Use arraysfiles=("file1" "file2" "file3")for file in "${files[@]}"; do process "$file"done
# Error handlingtrap 'echo "Error on line $LINENO"' ERRQ1037: How do you use awk for text processing?
Section titled “Q1037: How do you use awk for text processing?”Answer:
# Basic usageawk '{print $1}' file.txtawk -F: '{print $1, $6}' /etc/passwd
# Conditionalawk '$3 > 1000 {print $1, $3}' /etc/passwd
# Calculationsawk '{sum+=$1} END {print sum}' numbers.txt
# Multiple fieldsawk '{print "User:" $1 " UID:" $3 " Home:" $6}' /etc/passwd
# Patternsawk '/^root/ {print}' /etc/passwdawk 'NR==5 {print}' file.txt
# Field separatorawk -F: '{print NF}' /etc/passwdQ1038: How do you use sed for text manipulation?
Section titled “Q1038: How do you use sed for text manipulation?”Answer:
# Replace textsed 's/old/new/' file.txtsed 's/old/new/g' file.txtsed 's/old/new/2' file.txt
# In-place editingsed -i 's/old/new/g' file.txt
# Delete linessed '/pattern/d' file.txtsed '1,5d' file.txtsed '5d' file.txt
# Insert textsed '1i\Header line' file.txtsed '1a\New line' file.txt
# Regexsed -E 's/[0-9]+/[REDACTED]/g' file.txtQ1039: How do you process JSON in bash?
Section titled “Q1039: How do you process JSON in bash?”Answer:
# Using jqcat data.json | jq '.name'cat data.json | jq '.items[].id'cat data.json | jq 'map(select(.age > 25))'cat data.json | jq '.items | length'
# Create JSONjq -n '{name: "test", value: 42}'
# Modify JSONcat data.json | jq '.name = "new_name"'cat data.json | jq '.items += [{"id": 3}]'
# Filtercat data.json | jq '.items[] | select(.id == 2)'Q1040: How do you write Python scripts for Linux administration?
Section titled “Q1040: How do you write Python scripts for Linux administration?”Answer:
#!/usr/bin/env python3import subprocessimport osimport json
# Run shell commandsresult = subprocess.run(['df', '-h'], capture_output=True, text=True)print(result.stdout)
# Work with fileswith open('/etc/passwd', 'r') as f: for line in f: if 'admin' in line: print(line.strip())
# Parse JSONwith open('config.json', 'r') as f: config = json.load(f) print(config.get('database', {}))
# System infoimport platformimport socketprint(platform.uname())print(socket.gethostname())Linux Services
Section titled “Linux Services”Q1041: How do you configure Apache?
Section titled “Q1041: How do you configure Apache?”Answer:
# Installapt install apache2# oryum install httpd
# Configuration# /etc/apache2/apache2.conf (Debian)# /etc/httpd/conf/httpd.conf (RHEL)
# Virtual hosts# /etc/apache2/sites-available/example.conf<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>
# Enable sitea2ensite examplesystemctl reload apache2
# Modulesa2enmod ssl rewrite proxyQ1042: How do you configure Nginx?
Section titled “Q1042: How do you configure Nginx?”Answer:
# Installapt install nginx# oryum install nginx
# Configuration# /etc/nginx/nginx.conf
# Server block# /etc/nginx/sites-available/defaultserver { listen 80; server_name example.com;
root /var/www/html; index index.html;
location / { try_files $uri $uri/ =404; }
location /api { proxy_pass http://localhost:3000; }}
# Test confignginx -t
# Reloadsystemctl reload nginxQ1043: How do you configure MySQL/MariaDB?
Section titled “Q1043: How do you configure MySQL/MariaDB?”Answer:
# Installapt install mysql-server# oryum install mariadb-server
# Secure installationmysql_secure_installation
# Create database and usermysql -u root -pCREATE DATABASE myapp;CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'password';GRANT ALL PRIVILEGES ON myapp.* TO 'myuser'@'localhost';FLUSH PRIVILEGES;
# Configuration# /etc/mysql/mariadb.conf.d/50-server.cnf# key_buffer_size = 256M# max_connections = 200
# Backupmysqldump -u root -p myapp > backup.sqlmysql -u root -p myapp < backup.sqlQ1044: How do you configure PostgreSQL?
Section titled “Q1044: How do you configure PostgreSQL?”Answer:
# Installapt install postgresql# oryum install postgresql-server
# Initializepostgresql-setup --initdb# orpg_ctl -D /var/lib/pgsql/data initdb
# Create user and databasesudo -u postgres createuser myusersudo -u postgres createdb mydbsudo -u postgres psqlALTER USER myuser WITH PASSWORD 'password';GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
# Configuration# /var/lib/pgsql/data/postgresql.conf# max_connections = 100# shared_buffers = 128MB
# Backuppg_dump -U myuser mydb > backup.sqlQ1045: How do you configure Redis?
Section titled “Q1045: How do you configure Redis?”Answer:
# Installapt install redis-server# oryum install redis
# Configuration# /etc/redis/redis.confbind 127.0.0.1port 6379maxmemory 256mbmaxmemory-policy allkeys-lruappendonly yes
# Commandsredis-cli PINGredis-cli SET mykey "value"redis-cli GET mykeyredis-cli KEYS "*"
# Cluster moderedis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 --cluster-replicas 1Linux Monitoring
Section titled “Linux Monitoring”Q1046: How do you set up Prometheus monitoring?
Section titled “Q1046: How do you set up Prometheus monitoring?”Answer:
# Installapt install prometheus# ortar -xzf prometheus-*.tar.gz
# Configuration# /etc/prometheus/prometheus.ymlglobal: scrape_interval: 15s
scrape_configs: - job_name: 'prometheus' static_configs: - targets: ['localhost:9090']
- job_name: 'node' static_configs: - targets: ['localhost:9100']
# Node exporter./node_exporter --collector.filesystem.mount-points-exclude="^/(sys|proc|dev|run)($|/)"
# View metricscurl http://localhost:9100/metricsQ1047: How do you configure Grafana?
Section titled “Q1047: How do you configure Grafana?”Answer:
# Installapt install grafana# oryum install grafana
# Startsystemctl start grafana-server# Default: admin/admin
# Add data source# HTTP URL: http://localhost:9090 (Prometheus)
# Create dashboard (JSON){ "dashboard": { "title": "System Monitoring", "panels": [ { "title": "CPU Usage", "type": "graph", "targets": [ { "expr": "100 - (avg by (instance) (irate(node_cpu_seconds_total{mode='idle'}[5m])) * 100)" } ] } ] }}Q1048: How do you set up ELK stack?
Section titled “Q1048: How do you set up ELK stack?”Answer:
# Install Elasticsearchapt install elasticsearchsystemctl enable elasticsearch
# Configure# /etc/elasticsearch/elasticsearch.ymlcluster.name: myclusternetwork.host: 0.0.0.0discovery.type: single-node
# Install Kibanaapt install kibana
# Install Logstashapt install logstash
# Filebeat configuration# /etc/filebeat/filebeat.ymlfilebeat.inputs: - type: log paths: - /var/log/*.logoutput.logstash: hosts: ["localhost:5044"]Q1049: How do you use Nagios?
Section titled “Q1049: How do you use Nagios?”Answer:
# Installapt install nagios4# oryum install nagios
# Create check script#!/bin/bash# /usr/local/nagios/lib/check_disk.shUSAGE=$(df -h / | tail -1 | awk '{print $5}' | sed 's/%//')if [ "$USAGE" -gt 90 ]; then echo "CRITICAL - Disk usage is ${USAGE}%" exit 2elif [ "$USAGE" -gt 80 ]; then echo "WARNING - Disk usage is ${USAGE}%" exit 1else echo "OK - Disk usage is ${USAGE}%" exit 0fi
# Define service# /etc/nagios4/conf.d/services.cfgdefine service{ host_name localhost service_description Disk Usage check_command check_disk check_interval 5}Q1050: How do you configure Zabbix?
Section titled “Q1050: How do you configure Zabbix?”Answer:
# Install Zabbix serverapt install zabbix-server-mysql zabbix-frontend-php
# Create databasemysql -u root -pCREATE DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_bin;CREATE USER 'zabbix'@'localhost' IDENTIFIED BY 'password';GRANT ALL PRIVILEGES ON zabbix.* TO 'zabbix'@'localhost';FLUSH PRIVILEGES;quit;
# Import schemazcat /usr/share/zabbix-sql-scripts/mysql/server.sql.gz | mysql -u zabbix -p zabbix
# Configure server# /etc/zabbix/zabbix_server.confDBPassword=password
# Install agentapt install zabbix-agent
# Configure agent# /etc/zabbix/zabbix_agentd.confServer=127.0.0.1ServerActive=127.0.0.1Hostname=Zabbix serverLinux Backup and Recovery
Section titled “Linux Backup and Recovery”Q1051: How do you use rsync for backups?
Section titled “Q1051: How do you use rsync for backups?”Answer:
# Basic syncrsync -av /source/ /destination/rsync -avz -e ssh user@remote:/remote/ /local/
# Delete files not in sourcersync -av --delete /source/ /destination/
# Exclude patternsrsync -av --exclude='*.log' --exclude='tmp/' /source/ /destination/
# Progress and bandwidthrsync -av --progress --bwlimit=1000 /source/ /destination/
# Dry runrsync -avn /source/ /destination/
# Script for automated backup#!/bin/bashrsync -avz --delete -e ssh /data/ backup@server:/backup/$(date +%Y%m%d)/Q1052: How do you use tar for backups?
Section titled “Q1052: How do you use tar for backups?”Answer:
# Create archivetar -cvf backup.tar /datatar -cvzf backup.tar.gz /datatar -cvjf backup.tar.bz2 /data
# Extracttar -xvf backup.tartar -xvzf backup.tar.gz
# List contentstar -tvf backup.tar
# Incremental backuptar -g /var/log/backup.snap -cvzf backup-incremental.tar.gz /data
# With datetar -cvzf backup-$(date +%Y%m%d).tar.gz /dataQ1053: How do you configure Bacula for backups?
Section titled “Q1053: How do you configure Bacula for backups?”Answer:
# Installapt install bacula-server bacula-client
# Configure Director# /etc/bacula/bacula-dir.confDirector { Name = bacula-dir DIRport = 9101 QueryFile = "/etc/bacula/query.sql" WorkingDirectory = "/var/lib/bacula" PidDirectory = "/var/run/bacula"}
# FileSetFileSet { Name = "Full Set" Include { Options { Signature = MD5 } File = /data } Exclude { File = /var/lib/bacula }}
# ScheduleSchedule { Name = "WeeklyCycle" Run = Full 1st sun at 23:05 Run = Incremental mon-sat at 23:05}Q1054: How do you use Duplicity for backups?
Section titled “Q1054: How do you use Duplicity for backups?”Answer:
# Installapt install duplicity
# Backup to localduplicity /data file:///backup/
# Backup to remoteduplicity /data sftp://user@remote//backup/
# Encrypted backupduplicity --encrypt-key ABC123 /data sftp://user@remote//backup/
# Restoreduplicity file:///backup/ /restore/duplicity --time 2024-01-01 sftp://user@remote//backup/ /restore/
# List filesduplicity list-current-files file:///backup/
# Verifyduplicity verify file:///backup/ /data/Q1055: How do you create a disaster recovery plan?
Section titled “Q1055: How do you create a disaster recovery plan?”Answer:
# 1. Document current system# Hardware inventorylshw > hardware_inventory.txtlspci >> hardware_inventory.txt
# Software inventorydpkg -l > installed_packages.txt# orrpm -qa > installed_packages.txt
# Network configurationip addr show > network_config.txtroute -n >> network_config.txtiptables-save > iptables_rules.txt
# Configuration filestar -cvzf configs.tar.gz /etc/
# 2. Test recovery# In VM/test environment# 1. Restore configs# 2. Verify services# 3. Test applicationsLinux Virtualization
Section titled “Linux Virtualization”Q1056: How do you configure KVM?
Section titled “Q1056: How do you configure KVM?”Answer:
# Installapt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils
# Check supportkvm-ok
# Create VMvirt-install \ --name webserver \ --ram 2048 \ --disk path=/var/lib/libvirt/images/webserver.qcow2,size=20 \ --vcpus 2 \ --os-type linux \ --os-variant ubuntu22.04 \ --network bridge=virbr0 \ --graphics vnc \ --console pty,target_type=serial \ --location 'http://archive.ubuntu.com/ubuntu/dists/jammy/main/installer-amd64/' \ --extra-args 'console=ttyS0'
# Manage VMsvirsh list --allvirsh start webservervirsh shutdown webservervirsh undefine webserverQ1057: How do you manage libvirt?
Section titled “Q1057: How do you manage libvirt?”Answer:
# Connectvirsh --connect qemu:///system
# Create network# /tmp/network.xml<network> <name>internal</name> <forward mode='nat'/> <ip address='192.168.100.1' netmask='255.255.255.0'> <dhcp> <range start='192.168.100.128' end='192.168.100.254'/> </dhcp> </ip></network>
virsh net-define /tmp/network.xmlvirsh net-start internal
# Snapshotvirsh snapshot-create-as webserver --name "before-update"virsh snapshot-list webservervirsh snapshot-revert webserver before-update
# Pool managementvirsh pool-listvirsh pool-info defaultQ1058: How do you configure QEMU?
Section titled “Q1058: How do you configure QEMU?”Answer:
# Run QEMUqemu-system-x86_64 \ -m 2048 \ -hda disk.img \ -cdrom ubuntu.iso \ -boot d \ -enable-kvm
# With networkqemu-system-x86_64 \ -m 2048 \ -hda disk.img \ -netdev user,id=net0,hostfwd=tcp::2222-:22 \ -device e1000,netdev=net0
# Snapshotsqemu-img create -f qcow2 -b base.img snapshot.imgqemu-img info snapshot.img
# Resize diskqemu-img resize disk.img +10G
# Convert imageqemu-img convert -O vmdk img.qcow2 img.vmdkQ1059: How do you troubleshoot virtualization issues?
Section titled “Q1059: How do you troubleshoot virtualization issues?”Answer:
# Check KVMlsmod | grep kvmcat /proc/cpuinfo | grep vmxvirt-host-validate
# View logsjournalctl -u libvirtddmesg | grep -i kvm
# Debug VMvirsh console webservervirsh dump webserver /tmp/core.qemu
# Network issuesbrctl showip link show virbr0
# Performancevirsh dominfo webservervirsh cpu-stats webserverQ1060: How do you configure LXC containers?
Section titled “Q1060: How do you configure LXC containers?”Answer:
# Installapt install lxc
# Create containerlxc-create -n mycontainer -t ubuntu
# Start containerlxc-start -n mycontainerlxc-attach -n mycontainer
# Configuration# /var/lib/lxc/mycontainer/configlxc.include = /usr/share/lxc/config/ubuntu.common.conflxc.arch = amd64lxc.rootfs.path = dir:/var/lib/lxc/mycontainer/rootfslxc.uts.name = mycontainerlxc.network.type = vethlxc.network.link = lxcbr0lxc.network.hwaddr = 00:16:3e:xx:xx:xx
# Clonelxc-copy -n mycontainer -N mycontainer2
# Snapshotslxc-snapshot -n mycontainerlxc-snapshot -n mycontainer -LLinux High Availability
Section titled “Linux High Availability”Q1061: How do you configure Keepalived?
Section titled “Q1061: How do you configure Keepalived?”Answer:
# Installapt install keepalived
vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 advert_int 1
authentication { auth_type PASS auth_pass mysecret }
virtual_ipaddress { 192.168.1.100 }
track_script { check_apache }}
vrrp_script check_apache { script "pkill -0 apache2" interval 2 weight 2}
# On backup server# priority 90# state BACKUPQ1062: How do you configure HAProxy?
Section titled “Q1062: How do you configure HAProxy?”Answer:
# Installapt install haproxy
global log /dev/log local0 maxconn 4096 user haproxy group haproxy
defaults log global mode http option httplog option dontlognull option redispatch retries 3 timeout connect 5000 timeout client 50000 timeout server 50000
frontend http-in bind *:80 default_backend app-servers
backend app-servers balance roundrobin server app1 192.168.1.10:8080 check server app2 192.168.1.11:8080 check server app3 192.168.1.12:8080 check backupQ1063: How do you configure Corosync/Pacemaker?
Section titled “Q1063: How do you configure Corosync/Pacemaker?”Answer:
# Installapt install pacemaker corosync pcs
# Configure corosync# /etc/corosync/corosync.conftotem { version: 2 cluster_name: mycluster transport: udpu interface { ringnumber: 0 bindnetaddr: 192.168.1.0 mcastport: 5405 }}
nodelist { node { ring0_addr: node1.example.com nodeid: 1 } node { ring0_addr: node2.example.com nodeid: 2 }}
quorum { provider: corosync_votequorum expected_votes: 2}
# Configure clusterpcs host auth node1 node2pcs cluster setup mycluster node1 node2pcs cluster start --allpcs cluster enable --all
# Add resourcespcs resource create VirtualIP ocf:heartbeat:IPaddr2 \ ip=192.168.1.100 cidr_netmask=24 op monitor interval=30spcs resource create WebService systemd:apache2 \ op monitor interval=30spcs constraint colocation add WebService VirtualIPQ1064: How do you configure DRBD?
Section titled “Q1064: How do you configure DRBD?”Answer:
# Installapt install drbd-utils
resource web { protocol C;
on node1 { device /dev/drbd0; disk /dev/sdb1; address 192.168.1.10:7788; meta-disk internal; }
on node2 { device /dev/drbd0; disk /dev/sdb1; address 192.168.1.11:7788; meta-disk internal; }}
# Initializedrbdadm create-md webdrbdadm up web
# Primarydrbdadm primary --force web
# Filesystemmkfs.xfs /dev/drbd0mount /dev/drbd0 /var/www
# Statuscat /proc/drbddrbdadm statusQ1065: How do you test high availability?
Section titled “Q1065: How do you test high availability?”Answer:
# Test failover# Node 1: Primarypcs status
# Stop cluster on node 1pcs cluster stop node1
# Verify IP moved to node 2ip addr showpcs status
# Test resourcepcs resource move WebService node2pcs status
# Failover test script#!/bin/bashecho "Starting failover test..."CURRENT=$(crm_mon -1 | grep -A1 "Master/Slave Set:" | tail -1 | awk '{print $3}')echo "Current primary: $CURRENT"
if [ "$CURRENT" == "node1" ]; then pcs cluster stop node1 sleep 10 echo "Checking failover..." pcs status | grep "VirtualIP"else pcs cluster stop node2 sleep 10 pcs status | grep "VirtualIP"fi
echo "Failover test completed"Linux DNS and DHCP
Section titled “Linux DNS and DHCP”Q1066: How do you configure BIND9?
Section titled “Q1066: How do you configure BIND9?”Answer:
# Installapt install bind9
options { directory "/var/cache/bind"; forwarders { 8.8.8.8; 8.8.4.4; }; dnssec-validation auto; listen-on { any; };};
# Zone file# /etc/bind/db.example.com$TTL 604800@ IN SOA ns1.example.com. admin.example.com. ( 2024010101 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL;@ IN NS ns1.example.com.@ IN A 192.168.1.10ns1 IN A 192.168.1.10www IN A 192.168.1.10
# Test configurationnamed-checkconfnamed-checkzone example.com /etc/bind/db.example.comQ1067: How do you configure DHCP server?
Section titled “Q1067: How do you configure DHCP server?”Answer:
# Installapt install isc-dhcp-server
default-lease-time 600;max-lease-time 7200;
subnet 192.168.1.0 netmask 255.255.255.0 { range 192.168.1.100 192.168.1.200; option routers 192.168.1.1; option subnet-mask 255.255.255.0; option domain-name-servers 8.8.8.8, 8.8.4.4; option domain-name "example.com";}
host static-client { hardware ethernet 00:11:22:33:44:55; fixed-address 192.168.1.50;}
# Restartsystemctl restart isc-dhcp-server
# View leasescat /var/lib/dhcp/dhcpd.leasesQ1068: How do you configure Dnsmasq?
Section titled “Q1068: How do you configure Dnsmasq?”Answer:
# Installapt install dnsmasq
interface=eth0bind-interfacesdomain=example.comlocal=/example.com/
# DNSaddress=/example.com/192.168.1.10address=/www.example.com/192.168.1.10
# DHCPdhcp-range=192.168.1.100,192.168.1.200,12hdhcp-option=option:router,192.168.1.1dhcp-option=option:dns-server,192.168.1.1
# Static DHCPdhcp-host=00:11:22:33:44:55,192.168.1.50
# DNS forwardingserver=8.8.8.8server=8.8.4.4Q1069: How do you troubleshoot DNS issues?
Section titled “Q1069: How do you troubleshoot DNS issues?”Answer:
# Query DNSdig example.comdig @8.8.8.8 example.comnslookup example.comhost example.com
# DNS zone transferdig axfr example.com @ns1.example.com
# Reverse lookupdig -x 192.168.1.10
# Trace DNS resolutiondig +trace example.com
# Check DNS serverdig +short myip.opendns.com @resolver1.opendns.com
# Flush DNS cachesystemd-resolve --flush-caches# or/etc/init.d/nscd restart# orresolvectl flush-cachesQ1070: How do you configure split DNS?
Section titled “Q1070: How do you configure split DNS?”Answer:
# BIND configuration for split DNS# Internal viewview "internal" { match-clients { 192.168.0.0/16; };
zone "example.com" { type master; file "db.internal.example.com"; };};
# External viewview "external" { match-clients { any; };
zone "example.com" { type master; file "db.external.example.com"; };};
# Using different A records# Internal: 192.168.1.10# External: 203.0.113.10
# Test from internaldig @internal-dns.example.com www.example.com +short
# Test from externaldig @external-dns.example.com www.example.com +shortLinux Mail Server
Section titled “Linux Mail Server”Q1071: How do you configure Postfix?
Section titled “Q1071: How do you configure Postfix?”Answer:
# Installapt install postfix
myhostname = mail.example.commydomain = example.commyorigin = $mydomaininet_interfaces = allmydestination = $myhostname, localhost, localhost.localdomainhome_mailbox = Maildir/smtpd_sasl_type = dovecotsmtpd_sasl_path = private/authsmtpd_sasl_auth_enable = yessmtpd_recipient_restrictions = permit_sasl_authenticated, reject
# Virtual aliases# /etc/postfix/virtualadmin@example.com adminsupport@example.com support@company.com
# Master.cfsubmission inet n - y - - smtpd -o syslog_name=postfix/submission
# Testpostfix checkpostfix reloadQ1072: How do you configure Dovecot?
Section titled “Q1072: How do you configure Dovecot?”Answer:
# Installapt install dovecot-imapd dovecot-pop3d
protocols = imap pop3listen = *base_dir = /var/run/dovecot/
# Authentication# /etc/dovecot/conf.d/10-auth.confdisable_plaintext_auth = yesauth_mechanisms = plain login
# User database# /etc/dovecot/conf.d/10-mail.confmail_location = maildir:~/Maildir
# PAMpassdb { driver = pam args = session_failure_delay=finite_secs}
# SSL# /etc/dovecot/conf.d/10-ssl.confssl = requiredssl_cert = </etc/ssl/certs/dovecot.pemssl_key = </etc/ssl/private/dovecot.pemQ1073: How do you configure spam filtering?
Section titled “Q1073: How do you configure spam filtering?”Answer:
# Install SpamAssassinapt install spamassassin spamc
# Configure Postfix# /etc/postfix/master.cfspamassassin unix - n n - - pipe user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}
# /etc/postfix/main.cfcontent_filter = spamassassin
# Configure SpamAssassin# /etc/spamassassin/local.cfrequired_score 5.0rewrite_header Subject [SPAM]report_safe 0
# Add headersadd_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_add_header all Reply-To _ADDR_
# Train bayessa-learn --spam /var/virusmails/*sa-learn --ham /var/mail/*Q1074: How do you configure mail relay?
Section titled “Q1074: How do you configure mail relay?”Answer:
# Postfix relay configurationrelayhost = [smtp.example.com]:587smtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_sasl_tls_security_level = encryptsmtp_tls_security_level = encryptsmtp_tls_wrappermode = no
# /etc/postfix/sasl_passwd[smtp.example.com]:587 username:password
# Secure the password filechmod 600 /etc/postfix/sasl_passwdpostmap /etc/postfix/sasl_passwd
# Relay for specific domains# /etc/postfix/transportexample.com :[smtp.example.com]* smtp:relay.other.com
# Testecho "Test email" | sendmail -v user@example.comQ1075: How do you troubleshoot mail issues?
Section titled “Q1075: How do you troubleshoot mail issues?”Answer:
# Check mail queuemailqpostqueue -p
# View mail logtail -f /var/log/mail.logjournalctl -u postfix -f
# Flush queuepostfix flushpostqueue -f
# Check specific mailpostcat -q <queue_id>
# Remove stuck mailpostsuper -d <queue_id>postsuper -d ALL deferred
# Test SMTPtelnet mail.example.com 25nc -C mail.example.com 25
# Check deliveryecho "Test" | mail -v user@example.comLinux LDAP
Section titled “Linux LDAP”Q1076: How do you configure OpenLDAP?
Section titled “Q1076: How do you configure OpenLDAP?”Answer:
# Installapt install slapd ldap-utils
# Reconfiguredpkg-reconfigure slapd
# Add entries# add_user.ldifdn: uid=john,ou=people,dc=example,dc=comobjectClass: inetOrgPersonobjectClass: posixAccountuid: johncn: John Doesn: DoegivenName: JohnuidNumber: 1000gidNumber: 1000homeDirectory: /home/johnmail: john@example.com
# Add entryldapadd -x -D "cn=admin,dc=example,dc=com" -W -f add_user.ldif
# Searchldapsearch -x -b "dc=example,dc=com" "(uid=john)"ldapsearch -x -H ldap://localhost -D "cn=admin,dc=example,dc=com" -WQ1077: How do you integrate Linux with LDAP?
Section titled “Q1077: How do you integrate Linux with LDAP?”Answer:
# Install clientapt install libnss-ldap libpam-ldap ldap-utils
# Configure NSS# /etc/nsswitch.confpasswd: compat ldapgroup: compat ldapshadow: compat ldaphosts: files dns ldapnetworks: files ldap
# Configure PAM# /etc/pam.d/common-sessionsession optional pam_mkhomedir.so skel=/etc/skel umask=077
# Configure LDAP client# /etc/ldap.confbase dc=example,dc=comuri ldap://ldap.example.comldap_version 3rootbinddn cn=admin,dc=example,dc=com
# Testgetent passwd johnid johnQ1078: How do you configure LDAP replication?
Section titled “Q1078: How do you configure LDAP replication?”Answer:
# Master (provider) configurationoverlay syncprovsyncprov-checkpoint 100 10syncprov-sessionlog 100
# Enable syncprov modulemodulepath /usr/lib/ldapmoduleload syncprov
# Consumer (replica) configuration# /etc/ldap/slapd.confsyncrepl rid=123 provider=ldap://master.example.com:389 type=refreshAndPersist searchbase="dc=example,dc=com" bindmethod=simple binddn="cn=admin,dc=example,dc=com" credentials=secret retry="60 +"
# Or use LDAP URLsyncrepl rid=123 provider=ldap://master.example.com:389 searchbase="dc=example,dc=com" binddn="cn=syncuser,dc=example,dc=com" credentials=passwordQ1079: How do you secure LDAP?
Section titled “Q1079: How do you secure LDAP?”Answer:
# TLS/SSL configurationTLS_CACERT /etc/ssl/certs/ca-certificates.crtTLS_REQCERT demand
# Enable TLS in slapd# /etc/default/slapdSLAPD_SERVICES="ldap://localhost/ ldap://localhost:7389/ ldaps://localhost:636/"
# Generate certificatesopenssl req -new -x509 -nodes -days 365 \ -keyout /etc/ldap/tls/ldap.key \ -out /etc/ldap/tls/ldap.crt
# Restrict access# /etc/ldap/slapd.confaccess to dn.base="" by * readaccess to * by self write by dn="cn=admin,dc=example,dc=com" write by * readQ1080: How do you backup and restore LDAP?
Section titled “Q1080: How do you backup and restore LDAP?”Answer:
# Backup databaseslapcat -n 1 > backup.ldif# or using ldapsearchldapsearch -x -LLL -b "dc=example,dc=com" > backup.ldif
# Restore# Stop slapdsystemctl stop slapd# Remove databaserm -rf /var/backups/ldap/*# Restoreslapadd -l backup.ldif# Set permissionschown -R openldap:openldap /var/lib/ldap/# Start slapdsystemctl start slapd
# Automate backup#!/bin/bashDATE=$(date +%Y%m%d)slapcat -n 1 > /backup/ldap-$DATE.ldifgzip /backup/ldap-$DATE.ldiffind /backup -mtime +30 -deleteLinux Storage
Section titled “Linux Storage”Q1081: How do you configure iSCSI?
Section titled “Q1081: How do you configure iSCSI?”Answer:
# Install (initiator)apt install open-iscsi
# Discover targetsiscsiadm -m discovery -t st -p 192.168.1.10
# Loginiscsiadm -m node --targetname iqn.2010-01.com.example:storage.target1 --login
# Configure auto-loginiscsiadm -m node -p 192.168.1.10 -o update -n node.startup -v automatic
# View sessionsiscsiadm -m sessioniscsiadm -m session -P 3
# Use devicefdisk -l /dev/sdbmkfs.xfs /dev/sdb1
# Logoutiscsiadm -m node --targetname iqn.2010-01.com.example:storage.target1 --logoutQ1082: How do you configure NFS?
Section titled “Q1082: How do you configure NFS?”Answer:
# Installapt install nfs-kernel-server
/data 192.168.1.0/24(rw,sync,no_subtree_check,no_root_squash)/backup 192.168.1.10(rw,sync,all_squash,anonuid=1000,anongid=1000)*(ro,async,no_subtree_check)
# Exportexportfs -aexportfs -r
# Client mountmount -t nfs 192.168.1.10:/data /mnt/data
# /etc/fstab192.168.1.10:/data /mnt/data nfs defaults,_netdev 0 0
# Options# rw/sync - read-write/synchronous# no_subtree_check - disable subtree checking# no_root_squash - allow root accessQ1083: How do you configure CIFS/SMB?
Section titled “Q1083: How do you configure CIFS/SMB?”Answer:
# Installapt install samba
[global] workgroup = WORKGROUP server string = File Server security = user map to guest = bad user dns proxy = no
[shared] path = /srv/samba/shared browsable = yes writable = yes guest ok = yes read only = no
[private] path = /srv/samba/private valid users = @smbgroup writable = yes browseable = no
# Create useruseradd -m smbusersmbpasswd -a smbuser
# Test configtestparm
# Clientmount -t cifs //server/share /mnt -o user=smbuserQ1084: How do you configure Ceph storage?
Section titled “Q1084: How do you configure Ceph storage?”Answer:
# Installapt install ceph-mon ceph-osd ceph-mds
# Create clusterceph-deploy new mon1 osd1 osd2
# Deploy monitorsceph-deploy mon create mon1
# Deploy OSDsceph-deploy osd create --data /dev/sdb1 mon1ceph-deploy osd create --data /dev/sdb1 osd1
# Create filesystemceph osd pool create cephfs_data 128ceph osd pool create cephfs_metadata 128ceph fs new cephfs cephfs_metadata cephfs_data
# Mount# Kernelmount -t ceph mon1:6789:/ /mnt/ceph
# FUSEceph-fuse -n client.admin /mnt/cephQ1085: How do you manage storage tiers?
Section titled “Q1085: How do you manage storage tiers?”Answer:
# Using lvmcachelvcreate --type cache --cachevol cachevol --pool vg_data/lv_data vg_data/cachepool
# Using btrfsmkfs.btrfs -d single -m single /dev/sda1 /dev/sdb1
# Using mdadm with SSD cachemdadm --create /dev/md0 --level=5 --raid-devices=3 /dev/sd[a-c]1mdadm --manage /dev/md0 --add /dev/sdd1
# ZFSzpool create data mirror /dev/sda1 /dev/sdb1 cache /dev/sdc1
#查看状态zpool statuszpool listzfs get allLinux Kernel
Section titled “Linux Kernel”Q1086: How do you compile a custom Linux kernel?
Section titled “Q1086: How do you compile a custom Linux kernel?”Answer:
# Install build dependenciesapt build-dep linuxapt install git bc bison flex libssl-dev
# Download sourcegit clone --depth 1 https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.gitcd linux
# Configuremake menuconfig# ormake xconfig# or copy current configcp /boot/config-$(uname -r) .configmake olddefconfig
# Buildmake -j$(nproc)make modules_installmake install
# Update boot loaderupdate-grub
# Reboot to new kernelrebootQ1087: How do you tune kernel parameters?
Section titled “Q1087: How do you tune kernel parameters?”Answer:
# View parameterssysctl -acat /proc/sys/.../...
# Set temporarilysysctl -w net.ipv4.ip_forward=1
# Set permanently# /etc/sysctl.confnet.ipv4.ip_forward=1vm.swappiness=10net.core.somaxconn=1024
# Applysysctl -p
# For specific interfacesysctl -w net.ipv4.tcp_congestion_control=bbr
# Network performancenet.core.rmem_max=16777216net.core.wmem_max=16777216net.ipv4.tcp_rmem="4096 87380 16777216"net.ipv4.tcp_wmem="4096 65536 16777216"Q1088: How do you load kernel modules?
Section titled “Q1088: How do you load kernel modules?”Answer:
# List moduleslsmodmodinfo module_name
# Load modulemodprobe module_name
# Unload modulemodprobe -r module_name
# Module parametersmodprobe module_name parameter=value
# Persistent configuration# /etc/modprobe.d/blacklist.confblacklist module_name
# /etc/modprobe.d/module.confoptions module_name parameter=value
# Create module dependencydepmod -a
# View module infomodinfo -p module_nameQ1089: How do you diagnose kernel issues?
Section titled “Q1089: How do you diagnose kernel issues?”Answer:
# Kernel messagesdmesgdmesg | taildmesg -T | grep -i error
# Kernel panic# Check /var/log/kern.logtail -f /var/log/kern.log
# Kernel configurationzcat /proc/config.gz# orcat /boot/config-$(uname -r)
# System callsstrace -c ./programstrace -e openat ls
# Kernel debuggingecho 1 > /proc/sys/kernel/debug/earlyprintkecho "debug" > /sys/power/state
# OOM killerdmesg | grep -i "out of memory"cat /var/log/syslog | grep -i oomQ1090: How do you secure the Linux kernel?
Section titled “Q1090: How do you secure the Linux kernel?”Answer:
# Kernel hardeningkernel.dmesg_restrict=1kernel.kptr_restrict=2kernel.yama.ptrace_scope=2kernel.sysrq=0net.ipv4.conf.all.rp_filter=1net.ipv4.conf.default.rp_filter=1net.ipv4.icmp_echo_ignore_broadcasts=1net.ipv4.conf.all.accept_redirects=0net.ipv4.conf.default.accept_redirects=0
# Disable unused filesystems# /etc/modprobe.d/disable-filesystems.confinstall squashfs /bin/trueinstall udf /bin/true
# Disable IPv6 if not needed# /etc/sysctl.confnet.ipv6.conf.all.disable_ipv6=1net.ipv6.conf.default.disable_ipv6=1Linux Automation
Section titled “Linux Automation”Q1091: How do you use Ansible?
Section titled “Q1091: How do you use Ansible?”Answer:
---- name: Configure webserver hosts: webservers become: yes vars: http_port: 80
tasks: - name: Install Apache apt: name: apache2 state: present when: ansible_os_family == "Debian"
- name: Start Apache service: name: apache2 state: started enabled: yes
- name: Copy config template: src: templates/httpd.conf.j2 dest: /etc/apache2/apache2.conf notify: restart apache
handlers: - name: restart apache service: name: apache2 state: restartedQ1092: How do you use Terraform for Linux infrastructure?
Section titled “Q1092: How do you use Terraform for Linux infrastructure?”Answer:
terraform { required_version = ">= 1.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 4.0" } }}
provider "aws" { region = "us-east-1"}
resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" subnet_id = aws_subnet.main.id
tags = { Name = "webserver" }
user_data = <<-EOF #!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd EOF}
resource "aws_security_group" "web" { name = "web-sg"
ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] }}Q1093: How do you use Chef?
Section titled “Q1093: How do you use Chef?”Answer:
package 'httpd' do package_name case node['platform'] when 'centos', 'redhat', 'amazon' then 'httpd' when 'debian', 'ubuntu' then 'apache2' end action :installend
service 'httpd' do case node['platform'] when 'centos', 'redhat', 'amazon' then service_name 'httpd' when 'debian', 'ubuntu' then service_name 'apache2' end action [:enable, :start]end
template '/var/www/html/index.html' do source 'index.html.erb' mode '0644' owner 'root' group 'root'end
# Run chefchef-client --local-mode recipe.rb# orknife solo bootstrap user@serverQ1094: How do you use Puppet?
Section titled “Q1094: How do you use Puppet?”Answer:
node 'webserver.example.com' { # Install package package { 'apache2': ensure => installed, }
# Manage service service { 'apache2': ensure => running, enable => true, require => Package['apache2'], }
# Manage file file { '/var/www/html/index.html': ensure => file, content => template('webserver/index.html.erb'), mode => '0644', require => Service['apache2'], }}# Runpuppet agent --test# orpuppet apply manifests/site.ppQ1095: How do you use Vagrant?
Section titled “Q1095: How do you use Vagrant?”Answer:
# VagrantfileVagrant.configure("2") do |config| config.vm.box = "ubuntu/jammy64"
config.vm.network "private_network", ip: "192.168.33.10" config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.synced_folder "./data", "/vagrant_data"
config.vm.provider "virtualbox" do |vb| vb.memory = "2048" vb.cpus = 2 end
config.vm.provision "shell", inline: <<-SHELL apt update apt install -y apache2 SHELLend
# Commandsvagrant upvagrant sshvagrant haltvagrant destroyvagrant provisionLinux Troubleshooting
Section titled “Linux Troubleshooting”Q1096: How do you troubleshoot slow systems?
Section titled “Q1096: How do you troubleshoot slow systems?”Answer:
# CPU usagetophtopps aux --sort=-%cpu | head
# Memoryfree -hvmstat 1pmap -x <pid>
# I/Oiostat -xz 1iotopsar -b 1
# Networknetstat -iss -s
# Process analysisstrace -c <command>perf top
# System resourcesuptimecat /proc/loadavgQ1097: How do you troubleshoot disk space issues?
Section titled “Q1097: How do you troubleshoot disk space issues?”Answer:
# Disk usagedf -hdf -i
# Largest directoriesdu -sh /*du -sh /var/*du -shx /var/* | sort -rh | head
# Largest filesfind / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -h
# Log filesjournalctl --disk-usagedu -sh /var/log/*find /var/log -type f -mtime +7 -delete
# Deleted but open fileslsof +L1ls -l /proc/*/fd/* | grep deletedQ1098: How do you troubleshoot network issues?
Section titled “Q1098: How do you troubleshoot network issues?”Answer:
# Interface statusip linkip addrethtool eth0
# Routingip routeip route get 8.8.8.8
# DNSgetent hosts example.comdig +trace example.com
# Connectivityping -c 4 8.8.8.8traceroute 8.8.8.8mtr 8.8.8.8
# Portsss -tulpnnetstat -tulpn
# Firewalliptables -L -n -vfirewall-cmd --list-all
# Traffic capturetcpdump -i eth0 host 192.168.1.1tcpdump -i eth0 port 80Q1099: How do you troubleshoot service failures?
Section titled “Q1099: How do you troubleshoot service failures?”Answer:
# Service statussystemctl status service-namejournalctl -u service-name -n 50journalctl -u service-name --since "1 hour ago"
# Service logscat /var/log/service/name.logtail -f /var/log/syslog | grep service
# Configuration testapache2ctl configtestnginx -tnamed-checkconf
# Check permissionsls -la /etc/service/ls -l /var/run/service/
# Dependenciessystemctl list-dependencies service-namesystemctl daemon-reload
# Process issuesps aux | grep servicelsof -p <pid>strace -p <pid>Q1100: How do you troubleshoot performance bottlenecks?
Section titled “Q1100: How do you troubleshoot performance bottlenecks?”Answer:
# Overall systemtophtopatopsar -A 1 5
# CPUmpstat -P ALL 1pidstat -p <pid> 1
# Memorypmap -x <pid>cat /proc/<pid>/status
# I/Oiostat -xz 1pidstat -d 1
# Networknethogsiftopsar -n DEV 1
# Applicationperf record -g -p <pid>perf report
# System callsstrace -c -p <pid>strace -tt -p <pid>Linux Cloud Integration
Section titled “Linux Cloud Integration”Q1101: How do you configure AWS EC2 instance?
Section titled “Q1101: How do you configure AWS EC2 instance?”Answer:
# Install AWS CLIapt install awscli# orpip install awscli
# Configureaws configure# AWS Access Key ID: ***# AWS Secret Access Key: ***# Default region name: us-east-1# Default output format: json
# EC2 commandsaws ec2 describe-instancesaws ec2 start-instances --instance-ids i-1234567890abcdef0aws ec2 stop-instances --instance-ids i-1234567890abcdef0
# Instance metadatacurl http://169.254.169.254/latest/meta-data/curl http://169.254.169.254/latest/user-data/
# Install SSM Agentapt install amazon-ssm-agentQ1102: How do you use cloud-init?
Section titled “Q1102: How do you use cloud-init?”answer:
#cloud-configpackage_update: truepackages: - nginx - curl
write_files: - path: /var/www/html/index.html content: | <html> <h1>Hello from Cloud-Init</h1> </html> owner: root:root permissions: '0644'
runcmd: - systemctl enable nginx - systemctl start nginx - echo "192.168.1.10 webserver" >> /etc/hosts
users: - name: admin sudo: ALL=(ALL) NOPASSWD:ALL ssh_authorized_keys: - ssh-rsa AAAA...Q1103: How do you configure Docker on cloud?
Section titled “Q1103: How do you configure Docker on cloud?”Answer:
# Install Dockercurl -fsSL https://get.docker.com | sh
# Configure Docker daemon# /etc/docker/daemon.json{ "storage-driver": "overlay2", "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" }, "live-restore": true, "default-address-pools": [ {"base": "172.17.0.0/16", "size": 24} ]}
# Enable Docker servicesystemctl enable dockersystemctl start docker
# Docker swarm (for multi-host)docker swarm initdocker node lsQ1104: How do you configure Kubernetes on Linux?
Section titled “Q1104: How do you configure Kubernetes on Linux?”Answer:
# Install kubeadmapt-get update && apt-get install -y apt-transport-https curlcurl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | tee /etc/apt/sources.list.d/kubernetes.listapt-get updateapt-get install -y kubelet kubeadm kubectl
# Initialize clusterkubeadm init --pod-network-cidr=10.244.0.0/16
# Join nodeskubeadm join <master-ip>:6443 --token <token> --discovery-token-ca-cert-hash sha256:<hash>
# Install network pluginkubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
# Deploy applicationkubectl create deployment nginx --image=nginxkubectl expose deployment nginx --port=80 --type=LoadBalancerQ1105: How do you configure load balancer in cloud?
Section titled “Q1105: How do you configure load balancer in cloud?”Answer:
# AWS Application Load Balanceraws elbv2 create-load-balancer \ --name my-alb \ --subnets subnet-12345678 subnet-87654321 \ --security-groups sg-12345678
# Target groupaws elv2 create-target-group \ --name my-targets \ --protocol HTTP \ --port 80 \ --vpc vpc-12345678
# Register targetsaws elv2 register-targets \ --target-group-arn arn:aws:elasticloadbalancing:... \ --targets Id=i-12345678
# Listeneraws elv2 create-listener \ --load-balancer-arn arn:aws:elasticloadbalancing:... \ --protocol HTTP \ --port 80 \ --default-actions Type=forward,TargetGroupArn=arn:aws:...
# HAProxy load balancer (on-premise)# See HAProxy configuration earlierLinux Updates and Patching
Section titled “Linux Updates and Patching”Q1106: How do you automate security updates?
Section titled “Q1106: How do you automate security updates?”Answer:
# Install unattended-upgrades (Debian/Ubuntu)apt install unattended-upgrades
# Configure# /etc/apt/apt.conf.d/50unattended-upgradesUnattended-Upgrade::Allowed-Origins { "${distro_id}:${distro_codename}-security";};Unattended-Upgrade::Package-blacklist { "vim"; "apache2";};Unattended-Upgrade::Automatic-Reboot "true";Unattended-Upgrade::Automatic-Reboot-Time "02:00";
# Enabledpkg-reconfigure -plow unattended-upgrades
# RHEL/CentOSyum install yum-cron# /etc/yum/yum-cron.confapply_updates = yesdownload_updates = yes
# Testunattended-upgrades --dry-run --debugQ1107: How do you patch kernel live?
Section titled “Q1107: How do you patch kernel live?”Answer:
# Using kpatch (RHEL/CentOS)yum install kpatchkpatch install
# Build patchkpatch build patch.diff
# Applykpatch load kpatch-mypatch.ko
# Checkkpatch list
# Using livepatch (Ubuntu)snap install canonical-livepatchcanonical-livepatch enable <token>
# Check statuscanonical-livepatch statusQ1108: How do you manage package repositories?
Section titled “Q1108: How do you manage package repositories?”Answer:
# Debian/Ubuntudeb http://archive.ubuntu.com/ubuntu/ jammy main restricted universe multiversedeb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe multiverse
# Add repositoryadd-apt-repository ppa:nginx/stable
# Updateapt update
# RHEL/CentOS# /etc/yum.repos.d/*.repo[baseos]name=BaseOSbaseurl=https://dl.fedoraproject.org/pub/epel/$releasever/Everything/$basearchenabled=1
# Clean cacheapt cleanyum clean all
# List reposapt-cache policyyum repolistQ1109: How do you roll back updates?
Section titled “Q1109: How do you roll back updates?”Answer:
# Debian/Ubuntu# Hold packageapt-mark hold apache2
# View installed versionsapt-cache policy nginx
# Downgradeapt install nginx=1.18.0-*
# Snapshots with aptapt install apt-cloneapt-clone clone myserver-packagesapt-clone restore myserver-packages.tar.gz
# RPM rollback (RHEL)# yum historyyum historyyum history undo <transaction-id>
# Transactional updates (openSUSE)transactional-updateQ1110: How do you test updates in staging?
Section titled “Q1110: How do you test updates in staging?”Answer:
# Create test environmentvagrant up staging
# Run tests# In staging environmentapt updateDEBIAN_FRONTEND=noninteractive apt upgrade -y
# Test applicationcurl http://localhostsystemctl status myappjournalctl -u myapp -n 50
# Check logstail -f /var/log/syslog
# If issues# Rollbackvagrant destroy stagingvagrant up staging
# Production update with backup# Before updatetar -czf /backup/$(hostname)-$(date +%Y%m%d).tar.gz /etc /var/www
# Run updateapt update && apt upgrade -y
# If failedtar -xzf /backup/$(hostname)-backup.tar.gz -C /Linux Compliance
Section titled “Linux Compliance”Q1111: How do you implement CIS benchmarks?
Section titled “Q1111: How do you implement CIS benchmarks?”Answer:
# Install CIS benchmark toolapt install lynis
# Run auditlynis audit systemlynis audit --profile cis-ubuntu-22.04
# Key CIS controls# 1.1.1 Disable unused filesystemsecho "install cramfs /bin/true" > /etc/modprobe.d/cramfs.confecho "install squashfs /bin/true" > /etc/modprobe.d/squashfs.conf
# 1.5.1 Set bootloader passwordgrub-mkpasswd-pbkdf2# Add to /etc/grub.d/40_custom
# 3.1 Enable syncookiessysctl -w net.ipv4.tcp_syncookies=1
# 4.1 Configure auditd# See auditd configuration earlier
# Generate reportlynis audit system --html > report.htmlQ1112: How do you configure auditd?
Section titled “Q1112: How do you configure auditd?”Answer:
# Installapt install auditd
# Configure rules# /etc/audit/audit.rules# Watch files-w /etc/passwd -p wa -k passwd_changes-w /etc/shadow -p wa -k shadow_changes-w /etc/sudoers -p wa -k sudoers_changes
# Watch commands-a always,exit -F arch=b64 -S execve -F path=/usr/bin/wget -k network-download-a always,exit -F arch=b64 -S execve -F path=/usr/bin/curl -k network-download
# Watch directories-w /etc/httpd/conf/ -p wa -k httpd_conf
# Services-w /usr/sbin/service -p x -k service_management
# Generate reportaureport --summaryaureport --fileaureport --terminalQ1113: How do you implement FIPS 140-2?
Section titled “Q1113: How do you implement FIPS 140-2?”Answer:
# Enable FIPS (RHEL/CentOS)fips-mode-setup --enable
# Configure OpenSSL for FIPS# /etc/ssl/openssl.cnfopenssl_conf = openssl_init
[openssl_init]ssl_conf = ssl_sect
[ssl_sect]system_default = system_default_sect
[system_default_sect]CipherString = DEFAULT@SECLEVEL=2
# Check FIPS statuscat /proc/sys/crypto/fips_enabled
# Use FIPS certified algorithms# OpenSSLopenssl ciphers -v 'FIPS'
# SSH# /etc/ssh/sshd_configCiphers aes256-ctr,aes192-ctr,aes128-ctrMACs hmac-sha2-512,hmac-sha2-256KexAlgorithms diffie-hellman-group-exchange-sha256Q1114: How do you configure AIDE?
Section titled “Q1114: How do you configure AIDE?”Answer:
# Installapt install aide
# Configure# /etc/aide/aide.conf# Database locationdatabase=file:/var/lib/aide/aide.dbdatabase_out=file:/var/lib/aide/aide.db.new
# RulesFull = p+i+n+u+g+s+m+c+md5+sha256Lsof = p+u+g+i+n+S
# Files to monitor/etc p+inode+u+g+i+m+c+md5+sha256/bin p+inode+u+g+i+m+c+md5+sha256/sbin p+inode+u+g+i+m+c+md5+sha256/usr p+inode+u+g+i+m+c+md5+sha256
# Initialize databaseaideinit
# Check integrityaide --checkaide --update
# Schedule# /etc/cron.d/aide0 5 * * * root /usr/bin/aide --checkQ1115: How do you implement network segmentation?
Section titled “Q1115: How do you implement network segmentation?”Answer:
# VLAN isolationip link add link eth0 name eth0.100 type vlan id 100ip addr add 192.168.100.1/24 dev eth0.100
# iptables zonesiptables -N DMZiptables -A DMZ -j DROPiptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
# Network namespaces for isolationip netns add isolatedip netns exec isolated ip link set lo up
# Cgroups for process isolation# /etc/cgconfig.confgroup web { cpu { cpu.shares=512; } memory { memory.limit_in_bytes=512M; }}
# AppArmor/SELinuxapparmor_parser -r /etc/apparmor.d/*Linux Services Advanced
Section titled “Linux Services Advanced”Q1116: How do you configure caching proxy?
Section titled “Q1116: How do you configure caching proxy?”Answer:
# Install Squidapt install squid
# Basic confighttp_port 3128cache_dir ufs /var/spool/squid 1000 16 256
# Access controlacl localnet src 192.168.0.0/16http_access allow localnethttp_access deny all
# Cache rulesrefresh_pattern -i \.jpg$ 10080 90% 43200refresh_pattern -i \.html$ 1440 90% 3600refresh_pattern -i \.css$ 10080 90% 43200refresh_pattern -i \.js$ 10080 90% 43200
# Transparent proxyhttp_port 3128 transparent
# Testsquid -k parsesystemctl restart squidQ1117: How do you configure reverse proxy?
Section titled “Q1117: How do you configure reverse proxy?”Answer:
# Nginx reverse proxyserver { listen 80; server_name api.example.com;
location / { proxy_pass http://backend:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }
location /admin { proxy_pass http://admin-backend:8081; auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.htpasswd; }}
# Cache with nginxproxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g inactive=60m;location / { proxy_cache api_cache; proxy_cache_valid 200 60m; proxy_pass http://backend:8080;}Q1118: How do you configure caching server?
Section titled “Q1118: How do you configure caching server?”Answer:
# Install Varnishapt install varnish
vcl 4.1;
backend default { .host = "127.0.0.1"; .port = "8080"; .probe = { .url = "/health"; .timeout = 5s; .interval = 10s; }}
sub vcl_recv { # Don't cache admin pages if (req.url ~ "^/admin") { return (pass); }
# Don't cache POST requests if (req.method == "POST") { return (pass); }}
sub vcl_backend_response { # Cache static files if (bereq.url ~ "\.(jpg|jpeg|png|gif|ico|css|js)$") { set beresp.ttl = 24h; }}
# Commandsvarnishd -F -f /etc/varnish/default.vclvarnishstatvarnishlogQ1119: How do you configure web server tuning?
Section titled “Q1119: How do you configure web server tuning?”Answer:
# Apache tuning<IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxRequestWorkers 150 MaxConnectionsPerChild 0</IfModule>
# Nginx tuning# /etc/nginx/nginx.confworker_processes auto;worker_rlimit_nofile 65535;
events { worker_connections 65535; multi_accept on; use epoll;}
http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; keepalive_requests 1000;
open_file_cache max=10000 inactive=30s; open_file_cache_valid 60s; open_file_cache_min_uses 2;
gzip on; gzip_types text/plain text/css application/json application/javascript;}Q1120: How do you configure load balancing algorithms?
Section titled “Q1120: How do you configure load balancing algorithms?”Answer:
# HAProxy algorithms# Round Robin (default)backend servers balance roundrobin server s1 192.168.1.10:80 check server s2 192.168.1.11:80 check
# Least Connectionsbackend servers balance leastconn server s1 192.168.1.10:80 check server s2 192.168.1.11:80 check
# Source IP Hashbackend servers balance source server s1 192.168.1.10:80 check server s2 192.168.1.11:80 check
# URI Hashbackend servers balance uri server s1 192.168.1.10:80 check server s2 192.168.1.11:80 check
# Weightedbackend servers balance roundrobin server s1 192.168.1.10:80 weight 3 check server s2 192.168.1.11:80 weight 1 checkLinux Kernel Tuning
Section titled “Linux Kernel Tuning”Q1121: How do you optimize TCP stack?
Section titled “Q1121: How do you optimize TCP stack?”Answer:
# TCP buffer sizesnet.core.rmem_default=262144net.core.rmem_max=16777216net.core.wmem_default=262144net.core.wmem_max=16777216
# TCP settingsnet.ipv4.tcp_rmem=4096 87380 16777216net.ipv4.tcp_wmem=4096 65536 16777216net.ipv4.tcp_congestion_control=cubicnet.ipv4.tcp_fastopen=3net.ipv4.tcp_max_syn_backlog=8192
# TCP performancenet.core.netdev_max_backlog=65535net.ipv4.tcp_fin_timeout=15
# TCP keepalivenet.ipv4.tcp_keepalive_time=600net.ipv4.tcp_keepalive_intvl=60net.ipv4.tcp_keepalive_probes=5
# Applysysctl -pQ1122: How do you tune virtual memory?
Section titled “Q1122: How do you tune virtual memory?”Answer:
# Swappinessvm.swappiness=10vm.vfs_cache_pressure=50
# Memory managementvm.dirty_ratio=15vm.dirty_background_ratio=5vm.dirty_expire_centisecs=3000vm.dirty_writeback_centisecs=500
# Overcommitvm.overcommit_memory=1vm.overcommit_ratio=50
# Huge pagesvm.nr_hugepages=512
# Applysysctl -p
# Configure huge pagesecho 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
# Transparent huge pagesecho never > /sys/kernel/mm/transparent_hugepage/enabledecho never > /sys/kernel/mm/transparent_hugepage/defragQ1123: How do you optimize disk I/O?
Section titled “Q1123: How do you optimize disk I/O?”Answer:
# I/O Scheduler# Check currentcat /sys/block/sda/queue/scheduler
# Set deadline schedulerecho deadline > /sys/block/sda/queue/schedulerecho cfq > /sys/block/sda/queue/scheduler
# Make permanent# /etc/udev/rules.d/60-ioschedulers.rulesACTION=="add|change", KERNEL=="sda", SUBSYSTEM=="block", ATTR{queue/scheduler}="deadline"
# Block device settingsecho 4096 > /sys/block/sda/queue/read_ahead_kbecho 0 > /sys/block/sda/queue/rotationalecho 2 > /sys/block/sda/queue/rq_affinity
# Filesystem options# /etc/fstab/dev/sda1 / ext4 noatime,nodiratime,errors=remount-ro 0 1Q1124: How do you tune process limits?
Section titled “Q1124: How do you tune process limits?”Answer:
# Max open files* soft nofile 65535* hard nofile 65535root soft nofile 65535root hard nofile 65535
# Max processes* soft nproc 4096* hard nproc 8192
# Core dumps* soft core 0* hard core unlimited
# Locked memory* soft memlock unlimited* hard memlock unlimited
# Apply without logoutulimit -n 65535
# View limitsulimit -acat /proc/<pid>/limitsQ1125: How do you optimize network throughput?
Section titled “Q1125: How do you optimize network throughput?”Answer:
# Network card offloadingethtool -K eth0 tso onethtool -K eth0 gso onethtool -K eth0 gro onethtool -K eth0 rx onethtool -K eth0 tx on
# Ring bufferethtool -G eth0 rx 4096 tx 4096
# Interrupt coalescingethtool -C eth0 rx-usecs 100 tx-usecs 100
# Flow controlethtool -A eth0 rx on tx on
# Bonding for throughput# See earlier section on network bonding
# Multi-queue# Checkcat /sys/class/net/eth0/queues/rx-0/rps_cpus# Setecho ffffff > /sys/class/net/eth0/queues/rx-0/rps_cpusLinux Logging
Section titled “Linux Logging”Q1126: How do you configure rsyslog?
Section titled “Q1126: How do you configure rsyslog?”Answer:
# Modules$ModLoad imudp$UDPServerRun 514$ModLoad imtcp$InputTCPServerRun 514
# Templates$template RemoteLogs,"/var/log/%HOSTNAME%/%PROGRAMNAME%.log"$template DetailedLogs,"/var/log/%HOSTNAME%/%$year%/%$month%/%$day%/detail.log"
# Rules# Log everything to remote server*.* @@remote-server:514
# Local logging*.info;mail.none;authpriv.none /var/log/messagesauthpriv.* /var/log/securemail.* -/var/log/maillogcron.* /var/log/cron
# Filter by program:programname, isequal, "apache" /var/log/apache.log
# Stop processing& stopQ1127: How do you configure journald?
Section titled “Q1127: How do you configure journald?”Answer:
[Journal]Storage=persistentCompress=yesSystemMaxUse=500MSystemMaxFileSize=50MMaxRetentionSec=30day
# Forward to syslogForwardToSyslog=yesForwardToKMsg=noForwardToWall=no
# Rate limitingRateLimitIntervalSec=30sRateLimitBurst=1000
# View logsjournalctljournalctl -u nginxjournalctl --since "2024-01-01"journalctl --since "1 hour ago"journalctl -p errjournalctl -f
# Persistent storagemkdir -p /var/log/journalsystemd-tmpfiles --create --prefix /var/log/journalQ1128: How do you centralize logs?
Section titled “Q1128: How do you centralize logs?”Answer:
# ELK Stack
# Filebeat on clientsfilebeat.inputs: - type: log paths: - /var/log/*.log fields: type: syslogoutput.logstash: hosts: ["logstash:5044"]
# Logstash config# /etc/logstash/conf.d/01-input.confinput { beats { port => 5044 }}
# Filterfilter { if [type] == "syslog" { grok { match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" } } date { match => [ "syslog_timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ] } }}Q1129: How do you rotate logs?
Section titled “Q1129: How do you rotate logs?”Answer:
# Global settingsdailyrotate 14compressdelaycompressmissingoknotifemptycreate 0640 root adm
# Include configsinclude /etc/logrotate.d/
# Specific config# /etc/logrotate.d/nginx/var/log/nginx/*.log { daily missingok rotate 52 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate invoke-rc.d nginx rotate >/dev/null 2>&1 endscript}
# Testlogrotate -d /etc/logrotate.conflogrotate -f /etc/logrotate.d/nginxQ1130: How do you analyze logs efficiently?
Section titled “Q1130: How do you analyze logs efficiently?”Answer:
# Using grepgrep -i error /var/log/syslog | head -20grep -v "INFO" /var/log/app.log
# Using awkawk '/ERROR/ {print $1, $5}' /var/log/app.logawk '{print $NF}' /var/log/access.log | sort | uniq -c | sort -rn
# Using cutcut -d' ' -f1 /var/log/access.log | sort | uniq -c
# Using logrotate with logwatchapt install logwatch
# Using GoAccessgoaccess /var/log/nginx/access.log -o /var/www/html/report.html
# Using lnavlnav /var/log/sysloglnav /var/log/*.logLinux Backup Advanced
Section titled “Linux Backup Advanced”Q1131: How do you configure incremental backups?
Section titled “Q1131: How do you configure incremental backups?”Answer:
#!/bin/bashSOURCE="/data"BACKUP="/backup"DATE=$(date +%Y%m%d)
# Full backup on Sundayif [ $(date +%w) -eq 0 ]; then echo "Full backup" rm -rf $BACKUP/full cp -al $SOURCE $BACKUP/fullelse # Incremental backup echo "Incremental backup" rm -rf $BACKUP/incremental_$DATE cp -al $BACKUP/full $BACKUP/incremental_$DATE cd $BACKUP/full rsync -a --delete --link-dest=../incremental_$DATE $SOURCE/ .fi
# Restore# rsync -a --delete incremental_20240115/ /data/Q1132: How do you backup databases?
Section titled “Q1132: How do you backup databases?”Answer:
#!/bin/bashDB_NAME="mydb"DB_USER="backup"DB_PASS="password"BACKUP_DIR="/backup/mysql"DATE=$(date +%Y%m%d_%H%M%S)
# MySQL backupmysqldump -u$DB_USER -p$DB_PASS --single-transaction --routines --triggers $DB_NAME | gzip > $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz
# PostgreSQL backuppg_dump -U $DB_USER -F c -b -v -f $BACKUP_DIR/${DB_NAME}_${DATE}.dump $DB_NAME
# Retentionfind $BACKUP_DIR -name "*.sql.gz" -mtime +7 -deletefind $BACKUP_DIR -name "*.dump" -mtime +7 -delete
# Verifyzcat $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz | head -5
# Restore# mysql -u$DB_USER -p$DB_PASS $DB_NAME < backup.sql# pg_restore -U $DB_USER -d $DB_NAME backup.dumpQ1133: How do you configure remote backup?
Section titled “Q1133: How do you configure remote backup?”Answer:
#!/bin/bashSOURCE="/data"REMOTE="backup@remote.server:/backups/$(hostname)"DATE=$(date +%Y%m%d)
# Rsync over SSHrsync -avz --delete \ -e "ssh -i /root/.ssh/backup_key" \ --exclude='*.tmp' \ $SOURCE/ $REMOTE/daily/
# With compressionrsync -avz --delete -e ssh $SOURCE/ user@remote:/backup/
# Incremental with link-destrsync -avz --delete --link-dest=../last $SOURCE/ user@remote:/backup/$DATE/
# Verifyrsync -avnc --delete $SOURCE/ user@remote:/backup/Q1134: How do you test backup integrity?
Section titled “Q1134: How do you test backup integrity?”Answer:
# Check backup file integrity# Compressed filesgzip -t backup.tar.gzbzip2 -t backup.tar.bz2
# Checksumssha256sum backup.tar.gz > backup.sha256sha256sum -c backup.sha256
# Verify MySQL backupmysqlcheck -u root -p --all-databases# ormysql -u root -p -e "source backup.sql"
# Verify PostgreSQL backuppg_restore --list backup.dump | head
# Test restore in VMvagrant up testvagrant ssh test -c "mysql -u root -p mydb < /vagrant/backup.sql"vagrant ssh test -c "curl localhost"vagrant destroy test
# Automated verification#!/bin/bashif ! tar -tzf /backup/backup.tar.gz >/dev/null 2>&1; then echo "Backup is corrupted!" mail -s "Backup Failed" admin@example.comfiQ1135: How do you plan disaster recovery?
Section titled “Q1135: How do you plan disaster recovery?”Answer:
# Document everything# 1. Hardware inventorylshw > inventory/$(hostname)-hardware.txtlspci >> inventory/$(hostname)-hardware.txt
# 2. Software inventorydpkg -l > inventory/$(hostname)-packages.txt
# 3. Network configurationip addr show > network/$(hostname)-interfaces.txtroute -n >> network/$(hostname)-routes.txt
# 4. Services configurationtar -czf configs-$(hostname).tar.gz /etc/
# 5. Create recovery runbook# Step 1: Boot from rescue media# Step 2: Verify hardware# Step 3: Recreate partitions# Step 4: Restore OS# Step 5: Install packages# Step 6: Restore configurations# Step 7: Restore data# Step 8: Start services
# Test in DR sitevagrant up dr-test# Run recovery proceduresLinux Networking Advanced
Section titled “Linux Networking Advanced”Q1136: How do you configure QoS?
Section titled “Q1136: How do you configure QoS?”Answer:
# Traffic shaping with tc# Limit outgoing bandwidthtc qdisc add dev eth0 root handle 1: htb default 10tc class add dev eth0 parent 1: classid 1:10 htb rate 100mbit ceil 100mbittc class add dev eth0 parent 1: classid