Linux_Practical_Interview_1 100
Linux Practical Interview Questions (1-100)
Section titled “Linux Practical Interview Questions (1-100)”Linux Basics
Section titled “Linux Basics”Q1: How do you check the current kernel version?
Section titled “Q1: How do you check the current kernel version?”Answer:
# Check kernel versionuname -r# orcat /proc/version# orhostnamectlQ2: How do you check system uptime?
Section titled “Q2: How do you check system uptime?”Answer:
# Check uptimeuptime# oruptime -p # pretty format# orcat /proc/uptimeQ3: How do you view system memory usage?
Section titled “Q3: How do you view system memory usage?”Answer:
# Check memoryfree -h# orcat /proc/meminfo# orvmstat 1Q4: How do you check disk usage?
Section titled “Q4: How do you check disk usage?”Answer:
# Disk usagedf -h# ordu -sh /path/to/directory# orlsblkQ5: How do you check CPU information?
Section titled “Q5: How do you check CPU information?”Answer:
# CPU infocat /proc/cpuinfo# orlscpu# ortopFile System Commands
Section titled “File System Commands”Q6: How do you find files in Linux?
Section titled “Q6: How do you find files in Linux?”Answer:
# Find filesfind /path -name "filename"# Find by typefind /path -type f -name "*.log"# Find by sizefind /path -size +100M# Find by modified timefind /path -mtime -7Q7: How do you search inside files?
Section titled “Q7: How do you search inside files?”Answer:
# Search in filesgrep -r "search_term" /path# Case insensitivegrep -ri "search_term" /path# Show line numbersgrep -n "search_term" file# Use regexgrep -E "pattern" fileQ8: How do you use sed for text processing?
Section titled “Q8: How do you use sed for text processing?”Answer:
# Replace textsed 's/old/new/g' file# In-place editsed -i 's/old/new/g' file# Delete linessed '/pattern/d' file# Print specific linesed -n '5p' fileQ9: How do you use awk for text processing?
Section titled “Q9: How do you use awk for text processing?”Answer:
# Print columnsawk '{print $1}' file# Field separatorawk -F',' '{print $2}' file# Conditionalawk '$3 > 50 {print $1}' file# Sum valuesawk '{sum+=$1} END {print sum}' fileQ10: How do you compress and decompress files?
Section titled “Q10: How do you compress and decompress files?”Answer:
# gzip compressiongzip filegunzip file.gz
# tar archivetar -cvf archive.tar directory/tar -xvf archive.tartar -czvf archive.tar.gz directory/tar -xzvf archive.tar.gz
# zipzip -r archive.zip directory/unzip archive.zipUser and Permissions
Section titled “User and Permissions”Q11: How do you create and manage users?
Section titled “Q11: How do you create and manage users?”Answer:
# Create useruseradd username# or with home directoryuseradd -m username
# Set passwordpasswd username
# Add to groupusermod -aG groupname username
# Delete useruserdel username
# Check user infoid usernameQ12: How do you manage file permissions?
Section titled “Q12: How do you manage file permissions?”Answer:
# Change permissionschmod 755 filechmod +x script.shchmod -R 644 directory/
# Change ownerchown user:group file
# View permissionsls -l fileQ13: How do special permissions work?
Section titled “Q13: How do special permissions work?”Answer:
# SUID (set user ID)chmod 4755 file # or chmod u+s file
# SGID (set group ID)chmod 2755 directory # or chmod g+s directory
# Sticky bitchmod 1777 /tmp # or chmod +t /tmp
# Viewls -l file # shows s or tQ14: How do you use sudo configuration?
Section titled “Q14: How do you use sudo configuration?”Answer:
# Edit sudoers filevisudo
# Grant sudo accessusername ALL=(ALL:ALL) ALL
# Passwordless sudousername ALL=(ALL) NOPASSWD: ALLQ15: How do you check user sessions?
Section titled “Q15: How do you check user sessions?”Answer:
# Who is logged inwhow# Last loginlastlastlog# Current userwhoamiProcess Management
Section titled “Process Management”Q16: How do you view running processes?
Section titled “Q16: How do you view running processes?”Answer:
# View processespsps auxps -ef# Interactivetophtop# Tree viewpstreeQ17: How do you kill processes?
Section titled “Q17: How do you kill processes?”Answer:
# Kill by PIDkill -15 pid # SIGTERM (graceful)kill -9 pid # SIGKILL (force)kill -2 pid # SIGINT (Ctrl+C)
# Kill by namepkill process_namekillall process_name
# Kill processes by patternpgrep pattern | xargs killQ18: How do you manage background jobs?
Section titled “Q18: How do you manage background jobs?”Answer:
# Run in backgroundcommand &
# List jobsjobs
# Bring to foregroundfg %1
# Send to backgroundCtrl+Zbg %1
# Run nohupnohup command &Q19: How do you check process resource usage?
Section titled “Q19: How do you check process resource usage?”Answer:
# CPU and memorytophtop# Per-processps aux --sort=-%cpu | headps aux --sort=-%mem | head# Detailed/proc/PID/statusQ20: How do you manage services?
Section titled “Q20: How do you manage services?”Answer:
# SystemDsystemctl start servicesystemctl stop servicesystemctl restart servicesystemctl status servicesystemctl enable servicesystemctl disable service
# SysV initservice service_name startservice service_name stopNetworking
Section titled “Networking”Q21: How do you check network configuration?
Section titled “Q21: How do you check network configuration?”Answer:
# IP addressesip addrip link show
# Routing tableip routeroute -n
# DNScat /etc/resolv.confnslookup domaindig domain
# Network interfacesifconfigip linkQ22: How do you test network connectivity?
Section titled “Q22: How do you test network connectivity?”Answer:
# Pingping -c 4 hostping -i 0.5 host # interval
# Traceroutetraceroute hosttracepath host
# Port scanningnc -zv host 1-1000telnet host port
# DNS lookupnslookup domaindig domainhost domainQ23: How do you configure firewall?
Section titled “Q23: How do you configure firewall?”Answer:
# iptablesiptables -L -niptables -A INPUT -p tcp --dport 22 -j ACCEPTiptables -A INPUT -j DROPiptables-save > /etc/iptables/rules.v4
# firewalldfirewall-cmd --list-allfirewall-cmd --add-service=sshfirewall-cmd --add-port=8080/tcpfirewall-cmd --reload
# ufwufw statusufw allow sshufw enableQ24: How do you configure network bonding?
Section titled “Q24: How do you configure network bonding?”Answer:
# Create bond interfacecat /etc/sysconfig/network-scripts/ifcfg-bond0DEVICE=bond0BONDING_OPTS="mode=1 miimon=100"IPADDR=192.168.1.10NETMASK=255.255.255.0
# Add slavecat /etc/sysconfig/network-scripts/ifcfg-eth0DEVICE=eth0MASTER=bond0SLAVE=yesQ25: How do you use SSH key authentication?
Section titled “Q25: How do you use SSH key authentication?”Answer:
# Generate keyssh-keygen -t rsa -b 4096ssh-keygen -t ed25519
# Copy to serverssh-copy-id user@host# orssh user@host 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys' < ~/.ssh/id_rsa.pub
# SSH configcat ~/.ssh/configHost server HostName 192.168.1.10 User admin IdentityFile ~/.ssh/id_rsaDisk Management
Section titled “Disk Management”Q26: How do you create and manage partitions?
Section titled “Q26: How do you create and manage partitions?”Answer:
# List partitionsfdisk -llsblkparted -l
# Create partitionfdisk /dev/sdb# n (new), p (primary), w (write)
# Formatmkfs.ext4 /dev/sdb1mkfs.xfs /dev/sdb1
# Mountmount /dev/sdb1 /mnt/dataQ27: How do you create LVM?
Section titled “Q27: How do you create LVM?”Answer:
# Create physical volumepvcreate /dev/sdb1
# Create volume groupvgcreate vg_data /dev/sdb1
# Create logical volumelvcreate -L 10G -n lv_data vg_data
# Format and mountmkfs.ext4 /dev/vg_data/lv_datamount /dev/vg_data/lv_data /mnt/dataQ28: How do you resize LVM?
Section titled “Q28: How do you resize LVM?”Answer:
# Extend logical volumelvextend -L +10G /dev/vg_data/lv_dataresize2fs /dev/vg_data/lv_data
# Reduce logical volumeumount /mnt/datae2fsck -f /dev/vg_data/lv_dataresize2fs /dev/vg_data/lv_data 5Glvreduce -L 5G /dev/vg_data/lv_dataQ29: How do you create RAID?
Section titled “Q29: How do you create RAID?”Answer:
# Create RAID5mdadm --create /dev/md0 --level=5 --raid-devices=3 /dev/sdb1 /dev/sdc1 /dev/sdd1
# Monitor RAIDmdadm --detail /dev/md0
# Simulate failuremdadm /dev/md0 --set faulty /dev/sdb1
# Remove failed drivemdadm /dev/md0 --remove /dev/sdb1Q30: How do you check disk health?
Section titled “Q30: How do you check disk health?”Answer:
# SMART statussmartctl -a /dev/sdasmartctl -H /dev/sda
# Disk usagedf -hdu -sh /*
# I/O statsiostat -x 1iotopPackage Management
Section titled “Package Management”Q31: How do you use yum/dnf?
Section titled “Q31: How do you use yum/dnf?”Answer:
# Install packageyum install packagednf install package
# Updateyum updatednf update
# Searchyum search packagednf search package
# Removeyum remove packagednf autoremove
# List installedyum list installeddnf list installedQ32: How do you use apt?
Section titled “Q32: How do you use apt?”Answer:
# Updateapt updateapt upgrade
# Installapt install packageapt-get install package
# Removeapt remove packageapt autoremove
# Searchapt search package
# List installedapt list --installedQ33: How do you use zypper?
Section titled “Q33: How do you use zypper?”Answer:
# Installzypper install package
# Updatezypper update
# Removezypper remove package
# Searchzypper search packageQ34: How do you build from source?
Section titled “Q34: How do you build from source?”Answer:
# Download and extractwget urltar -xzvf file.tar.gz
# Configure./configure --prefix=/usr/local
# Buildmake
# Installmake install# orsudo make installQ35: How do you manage repositories?
Section titled “Q35: How do you manage repositories?”bash:
# yum add repoyum-config-manager --add-repo http://repo.example.com.repo
# apt add repoadd-apt-repository ppa:name/ppa# orecho "deb url" > /etc/apt/sources.list.d/file.listapt updateLog Management
Section titled “Log Management”Q36: How do you view system logs?
Section titled “Q36: How do you view system logs?”Answer:
# System logstail -f /var/log/messagestail -f /var/log/syslog
# Auth logstail -f /var/log/auth.logtail -f /var/log/secure
# Application logstail -f /var/log/nginx/access.log
# Journaljournalctljournalctl -u servicejournalctl -fQ37: How do you rotate logs?
Section titled “Q37: How do you rotate logs?”Answer:
# Logrotate configcat /etc/logrotate.d/nginx/var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate systemctl reload nginx > /dev/null endscript}Q38: How do you analyze logs efficiently?
Section titled “Q38: How do you analyze logs efficiently?”Answer:
# Grep patternsgrep ERROR /var/log/messagesgrep -c "pattern" file
# Awk analysisawk '/ERROR/ {count++} END {print count}' file
# Sort and countawk '{print $5}' access.log | sort | uniq -c | sort -rn
# Time-basedawk '$4 >= "[10/Oct/2023:10:00"' access.logQ39: How do you manage syslog?
Section titled “Q39: How do you manage syslog?”Answer:
# Rsyslog configcat /etc/rsyslog.conf# Rules*.info;mail.none;authpriv.none /var/log/messagesauthpriv.* /var/log/secure
# Filter by facility:programname, isequal, "nginx" /var/log/nginx.log& ~Q40: How do you use systemd journal?
Section titled “Q40: How do you use systemd journal?”Answer:
# View logsjournalctljournalctl -u nginx.servicejournalctl --since "1 hour ago"journalctl --since "2023-01-01"
# Priorityjournalctl -p err
# Followjournalctl -fShell Scripting
Section titled “Shell Scripting”Q41: How do you write a basic shell script?
Section titled “Q41: How do you write a basic shell script?”Answer:
#!/bin/bash# Comments
# VariablesNAME="John"echo "Hello $NAME"
# User inputread -p "Enter name: " NAME
# Conditionalsif [ "$NAME" == "John" ]; then echo "Hello John"fi
# Loopsfor i in {1..5}; do echo $idone
# Functionsfunction greet() { echo "Hello $1"}greet "World"Q42: How do you handle arguments?
Section titled “Q42: How do you handle arguments?”Answer:
#!/bin/bash# Argumentsecho $0 # Script nameecho $1 # First argumentecho $# # Number of argumentsecho $@ # All argumentsecho $$ # PID
# Loop through argumentsfor arg in "$@"; do echo $argdone
# Getoptswhile getopts "hvc:" opt; do case $opt in h) echo "Help";; v) echo "Version";; c) echo "Config: $OPTARG";; esacdoneQ43: How do you use arrays?
Section titled “Q43: How do you use arrays?”Answer:
# Define arrayarr=(one two three)arr[0]="one"
# Access elementsecho ${arr[0]}echo ${arr[@]}
# Lengthecho ${#arr[@]}
# Loopfor item in "${arr[@]}"; do echo $itemdone
# Add elementsarr+=("four")Q44: How do you use string operations?
Section titled “Q44: How do you use string operations?”Answer:
# Length${#string}
# Substring${string:position}${string:position:length}
# Replace${string/pattern/replacement}${string//pattern/replacement}
# Pattern removal${string#pattern} # shortest match${string##pattern} # longest match
# Case conversion${string^^}${string,,}Q45: How do you handle errors?
Section titled “Q45: How do you handle errors?”Answer:
#!/bin/bash# Exit on errorset -e
# Debug modeset -x
# Capture exit codecommandecho $?
# Trap errorstrap 'echo "Error on line $LINENO"' ERR
# Custom errorif [ ! -f "$file" ]; then echo "File not found" >&2 exit 1fiSystem Performance
Section titled “System Performance”Q46: How do you monitor CPU usage?
Section titled “Q46: How do you monitor CPU usage?”Answer:
# Real-timetophtop# orglances
# Per-processps aux --sort=-%cpu | head# orpidstat 1
# System-widempstat -P ALL 1sar -u 1Q47: How do you monitor memory usage?
Section titled “Q47: How do you monitor memory usage?”Answer:
# Check memoryfree -h# orcat /proc/meminfo
# Per-processps aux --sort=-%mem | head# orpmap -X PID
# Trendsvmstat 1sar -r 1Q48: How do you monitor I/O?
Section titled “Q48: How do you monitor I/O?”Answer:
# I/O statsiostat -x 1
# Per-process I/Oiotop
# Check I/O waitvmstat 1# Look at 'wa' column
# Block deviceslsblkblktraceQ49: How do you monitor network?
Section titled “Q49: How do you monitor network?”Answer:
# Network statsnetstat -sss -s
# Per-connectionnetstat -antss -ant
# BandwidthnethogsiftopbmonQ50: How do you find performance bottlenecks?
Section titled “Q50: How do you find performance bottlenecks?”Answer:
# System resource summarysar -A 1
# Load averageuptime# orcat /proc/loadavg
# Process analysisstrace -p PID # system callsltrace -p PID # library callsperf topBoot and Kernel
Section titled “Boot and Kernel”Q51: How do you manage systemd services?
Section titled “Q51: How do you manage systemd services?”Answer:
# Start/stopsystemctl start nginxsystemctl stop nginxsystemctl restart nginx
# Enable/disable bootsystemctl enable nginxsystemctl disable nginx
# Statussystemctl status nginxsystemctl is-active nginx
# Listsystemctl list-units --type=servicesystemctl list-unit-files --type=serviceQ52: How do you modify kernel parameters?
Section titled “Q52: How do you modify kernel parameters?”Answer:
# Temporarilysysctl -w net.ipv4.tcp_fin_timeout=30
# Persistentlyecho "net.ipv4.tcp_fin_timeout=30" >> /etc/sysctl.confsysctl -p
# View currentsysctl -asysctl net.ipv4.tcp_fin_timeoutQ53: How do you manage initramfs?
Section titled “Q53: How do you manage initramfs?”Answer:
# Update initramfsupdate-initramfs -u# ordracut -f
# List moduleslsinitramfs /boot/initrd.img-$(uname -r)Q54: How do you manage kernel modules?
Section titled “Q54: How do you manage kernel modules?”Answer:
# List loadedlsmod
# Load modulemodprobe module_name
# Unload modulemodprobe -r module_name
# View module infomodinfo module_name
# Blacklistecho "blacklist module_name" >> /etc/modprobe.d/blacklist.confQ55: How do you troubleshoot boot issues?
Section titled “Q55: How do you troubleshoot boot issues?”Answer:
# Check boot logsjournalctl -bdmesgdmesg | grep -i error
# Check failed servicessystemctl --failed
# Boot options# Edit GRUB and add: systemd.unit=emergency.targetBackup and Recovery
Section titled “Backup and Recovery”Q56: How do you create backups?
Section titled “Q56: How do you create backups?”Answer:
# Using tartar -czpf backup.tar.gz /path
# Using rsyncrsync -avz /source/ /destination/
# Using dddd if=/dev/sda of=/backup/sda.img
# Using dump/restoredump -0f /backup.dump /restore -rf /backup.dumpQ57: How do you automate backups?
Section titled “Q57: How do you automate backups?”Answer:
# Cron jobcrontab -e# Add: 0 2 * * * /backup.sh
# /backup.sh#!/bin/bashtar -czpf /backup/$(date +%Y%m%d).tar.gz /datafind /backup -type f -mtime +30 -deleteQ58: How do you restore from backup?
Section titled “Q58: How do you restore from backup?”Answer:
# Extract tartar -xzf backup.tar.gz -C /restore/path
# Rsync restorersync -avz /backup/ /restore/
# dd restoredd if=/backup/sda.img of=/dev/sdaQ59: How do you use LVM snapshots?
Section titled “Q59: How do you use LVM snapshots?”Answer:
# Create snapshotlvcreate -L 10G -s -n snap_name /dev/vg/lv
# Mount snapshotmount /dev/vg/snap /mnt/snap
# Remove snapshotlvremove /dev/vg/snapQ60: How do you use rsync?
Section titled “Q60: How do you use rsync?”Answer:
# Basic syncrsync -avz source/ destination/
# Dry runrsync -avzn source/ destination/
# Delete files not in sourcersync -avz --delete source/ destination/
# Exclude patternsrsync -avz --exclude='*.log' source/ destination/
# Progressrsync -avz --progress source/ destination/Security
Section titled “Security”Q61: How do you secure SSH?
Section titled “Q61: How do you secure SSH?”Answer:
# Edit /etc/ssh/sshd_configPermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesPort 2222MaxAuthTries 3ClientAliveInterval 300
# Restartsystemctl restart sshdQ62: How do you configure SELinux?
Section titled “Q62: How do you configure SELinux?”Answer:
# Check statusgetenforcesestatus
# Set modesetenforce 0 # permissivesetenforce 1 # enforcing
# Persistently# Edit /etc/selinux/configSELINUX=enforcing
# Manage contextschcon -t httpd_sys_content_t /var/www/htmlsemanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"Q63: How do you use fail2ban?
Section titled “Q63: How do you use fail2ban?”Answer:
# Installapt install fail2banyum install fail2ban
# Configurecat /etc/fail2ban/jail.local[sshd]enabled = trueport = sshmaxretry = 3bantime = 3600
# Check statusfail2ban-client statusfail2ban-client status sshdQ64: How do you audit file access?
Section titled “Q64: How do you audit file access?”Answer:
# Install auditapt install auditd
# Configure rulesauditctl -w /etc/passwd -p wa -k passwd_changesauditctl -w /var/www/html -p r -k web_access
# View logsausearch -k passwd_changesaureport -fQ65: How do you encrypt partitions?
Section titled “Q65: How do you encrypt partitions?”Answer:
# LUKS encryptioncryptsetup luksFormat /dev/sdb1cryptsetup luksOpen /dev/sdb1 crypt_volmkfs.ext4 /dev/mapper/crypt_volmount /dev/mapper/crypt_vol /mnt/data
# Closeumount /mnt/datacryptsetup luksClose crypt_volVirtualization
Section titled “Virtualization”Q66: How do you use Docker?
Section titled “Q66: How do you use Docker?”Answer:
# List containersdocker ps -a
# Run containerdocker run -d -p 8080:80 --name web nginx
# Build imagedocker build -t myimage .
# Managedocker start/stop/restart containerdocker exec -it container /bin/bashdocker logs -f containerdocker rm containerQ67: How do you manage Docker images?
Section titled “Q67: How do you manage Docker images?”Answer:
# List imagesdocker images
# Pull imagedocker pull nginx:latest
# Builddocker build -t myimage .
# Tagdocker tag myimage registry/myimage:v1
# Pushdocker push registry/myimage:v1
# Removedocker rmi imageQ68: How do you use Docker Compose?
Section titled “Q68: How do you use Docker Compose?”Answer:
version: '3'services: web: image: nginx ports: - "80:80" volumes: - ./html:/usr/share/nginx/html db: image: mysql environment: MYSQL_ROOT_PASSWORD: secret
# Commandsdocker-compose up -ddocker-compose downdocker-compose psdocker-compose logs -fQ69: How do you use KVM/QEMU?
Section titled “Q69: How do you use KVM/QEMU?”Answer:
# Installapt install qemu-kvm libvirt-daemon
# Create VMvirt-install --name vm1 --ram 2048 --disk size=20 --os-variant ubuntu20.04 --location http://archive.ubuntu.com/ubuntu/dists/focal/main/installer-amd64/
# Managevirsh list --allvirsh start vm1virsh shutdown vm1virsh destroy vm1Q70: How do you configure libvirt?
Section titled “Q70: How do you configure libvirt?”Answer:
# Pool managementvirsh pool-define-as default dir - - - - /var/lib/libvirt/imagesvirsh pool-start defaultvirsh pool-autostart default
# Networkvirsh net-define /etc/libvirt/qemu/networks/default.xmlvirsh net-start defaultMonitoring and alerting
Section titled “Monitoring and alerting”Q71: How do you set up Prometheus?
Section titled “Q71: How do you set up Prometheus?”Answer:
# Installdocker run -d -p 9090:9090 prom/prometheus
# prometheus.ymlglobal: scrape_interval: 15sscrape_configs: - job_name: 'node' static_configs: - targets: ['localhost:9100']
# Add node exporterdocker run -d -p 9100:9100 prom/node-exporterQ72: How do you use Nagios?
Section titled “Q72: How do you use Nagios?”Answer:
# Installapt install nagios4
# Add check to commands.cfgdefine command{ command_name check_disk command_line $USER1$/check_disk -w $ARG1$ -c $ARG2$}
# Add servicedefine service{ host_name localhost service_description Disk check_command check_disk!20%!10%}Q73: How do you set up Zabbix?
Section titled “Q73: How do you set up Zabbix?”Answer:
# Install Zabbix serverapt install zabbix-server-mysql zabbix-frontend-php
# Configure databasemysql -e "create database zabbix character set utf8 collate utf8_bin;"mysql zabbix < /usr/share/zabbix-sql.sql
# Add agentapt install zabbix-agent# Edit /etc/zabbix/zabbix_agentd.confServer=192.168.1.10Q74: How do you use Grafana?
Section titled “Q74: How do you use Grafana?”Answer:
# Installdocker run -d -p 3000:3000 grafana/grafana
# Add data source# POST /api/datasources{ "name": "Prometheus", "type": "prometheus", "url": "http://localhost:9090"}
# Create dashboard# Add panels with Prometheus queriesQ75: How do you set up ELK Stack?
Section titled “Q75: How do you set up ELK Stack?”Answer:
# Install Elasticsearchdocker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch
# Install Kibanadocker run -d -p 5601:5601 kibana
# Install Logstashdocker run -d -p 5044:5044 logstash
# Configure filebeat on clientsfilebeat.modules: - systemoutput.logstash: hosts: ["logstash:5044"]Automation
Section titled “Automation”Q76: How do you use Ansible?
Section titled “Q76: How do you use Ansible?”Answer:
[webservers]web1 ansible_host=192.168.1.10web2 ansible_host=192.168.1.11
# playbook.yml- hosts: webservers become: yes tasks: - name: Install nginx apt: name: nginx state: present - name: Start nginx service: name: nginx state: startedQ77: How do you use Puppet?
Section titled “Q77: How do you use Puppet?”Answer:
class nginx { package { 'nginx': ensure => installed, } service { 'nginx': ensure => running, enable => true, }}node 'webserver' { include nginx}Q78: How do you use Chef?
Section titled “Q78: How do you use Chef?”Answer:
package 'nginx' do action :installend
service 'nginx' do action [:enable, :start]end
template '/etc/nginx/nginx.conf' do source 'nginx.conf.erb' notifies :restart, 'service[nginx]'endQ79: How do you use Salt?
Section titled “Q79: How do you use Salt?”Answer:
nginx: pkg.installed: - name: nginx
service.running: - name: nginx - enable: True
# /srv/pillar/top.slsbase: 'web*': - nginxQ80: How do you use cron jobs?
Section titled “Q80: How do you use cron jobs?”Answer:
# Edit crontabcrontab -e
# Examples# Run daily at 2am0 2 * * * /backup.sh
# Run every 5 minutes*/5 * * * * /monitor.sh
# Run on specific days0 0 * * 0 /weekly.sh
# System cron (runs even if user not logged in)/etc/cron.d/mycronTroubleshooting
Section titled “Troubleshooting”Q81: How do you troubleshoot network issues?
Section titled “Q81: How do you troubleshoot network issues?”Answer:
# Check connectivityping 8.8.8.8ping google.com
# Check DNSnslookup google.comdig google.com
# Check routesip routetraceroute google.com
# Check portsnetstat -tulpnss -tulpn
# Check firewalliptables -L -nfirewall-cmd --list-all
# Check DNS resolutioncat /etc/resolv.confQ82: How do you troubleshoot disk issues?
Section titled “Q82: How do you troubleshoot disk issues?”Answer:
# Check disk spacedf -h
# Check inodesdf -i
# Find large filesdu -sh /* 2>/dev/null | sort -rh | head
# Check disk healthsmartctl -a /dev/sda
# Check for bad blocksbadblocks -sv /dev/sda
# Check filesystemfsck /dev/sda1Q83: How do you troubleshoot high load?
Section titled “Q83: How do you troubleshoot high load?”Answer:
# Check loaduptimetophtop
# Check processesps aux --sort=-%cpu | head
# Check memoryfree -h
# Check I/Oiostat -x 1iotop
# Check for zombie processesps aux | grep zombieQ84: How do you troubleshoot service failures?
Section titled “Q84: How do you troubleshoot service failures?”Answer:
# Check statussystemctl status service
# Check logsjournalctl -u service -n 50tail -f /var/log/messages
# Test manually/usr/sbin/nginx -t
# Check dependenciessystemctl list-dependencies nginx
# Check portsnetstat -tulpn | grep LISTENss -tulpn | grep LISTENQ85: How do you recover from forgotten root password?
Section titled “Q85: How do you recover from forgotten root password?”Answer:
# Boot into recovery mode# 1. Restart system# 2. Press Shift during boot# 3. Select "Advanced options"# 4. Select recovery mode# 5. Select "root"
# Mount filesystemmount -o remount,rw /
# Change passwordpasswd root
# RebootrebootDNS and DHCP
Section titled “DNS and DHCP”Q86: How do you configure BIND DNS?
Section titled “Q86: How do you configure BIND DNS?”Answer:
zone "example.com" { type master; file "forward.zone";};
zone "1.168.192.in-addr.arpa" { type master; file "reverse.zone";};
# forward.zone$TTL 86400@ IN SOA ns1.example.com. admin.example.com. ( 2023010101 ; Serial 3600 ; Refresh 1800 ; Retry 604800 ; Expire 86400 ) ; Minimum TTL@ IN NS ns1.example.com.ns1 IN A 192.168.1.10www IN A 192.168.1.20Q87: How do you configure DHCP server?
Section titled “Q87: How do you configure DHCP server?”Answer:
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; default-lease-time 600; max-lease-time 7200;}Q88: How do you use dig for DNS queries?
Section titled “Q88: How do you use dig for DNS queries?”Answer:
# Basic querydig example.com
# Query specific recorddig A example.comdig MX example.comdig NS example.com
# Reverse lookupdig -x 192.168.1.1
# Tracedig +trace example.com
# Query specific serverdig @8.8.8.8 example.comQ89: How do you manage DNS zones?
Section titled “Q89: How do you manage DNS zones?”Answer:
# Add recordnamed-checkzone example.com forward.zone
# Reloadrndc reload
# Add zonenamed-checkconf -z /etc/named.conf
# Test resolutiondig @localhost example.comnslookup example.com localhostQ90: How do you configure dynamic DNS?
Section titled “Q90: How do you configure dynamic DNS?”Answer:
# Client side (dhclient)protocol=dhcpuse=if, if=eth0server=dynupdate.example.comlogin=usernamepassword=secretmydomain.example.com
# Server side (nsupdate)nsupdateserver ns1.example.comupdate add host.example.com 3600 A 192.168.1.50sendWeb Servers
Section titled “Web Servers”Q91: How do you configure Nginx?
Section titled “Q91: How do you configure Nginx?”Answer:
worker_processes auto;worker_rlimit_nofile 65535;
events { worker_connections 4096; use epoll;}
http { include /etc/nginx/mime.types; default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log;
include /etc/nginx/conf.d/*.conf;}Q92: How do you configure Apache?
Section titled “Q92: How do you configure Apache?”Answer:
ServerRoot "/etc/apache2"Listen 80
LoadModule mpm_prefork_module modules/mod_mpm_prefork.soLoadModule authz_core_module modules/mod_authz_core.so
IncludeOptional mods-enabled/*.loadIncludeOptional mods-enabled/*.confInclude ports.confIncludeOptional conf-enabled/*.confIncludeOptional sites-enabled/*.conf
# Virtual host<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>Q93: How do you configure reverse proxy?
Section titled “Q93: How do you configure reverse proxy?”Answer:
# Nginx reverse proxyserver { listen 80; server_name api.example.com;
location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_cache_bypass $http_upgrade; }}Q94: How do you configure SSL/TLS?
Section titled “Q94: How do you configure SSL/TLS?”Answer:
# Generate CSRopenssl req -new -newkey rsa:4096 -nodes -keyout server.key -out server.csr
# Generate self-signedopenssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
# Nginx configserver { listen 443 ssl http2; ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5;}Q95: How do you configure load balancing?
Section titled “Q95: How do you configure load balancing?”Answer:
# Nginx load balancerupstream backend { least_conn; server 192.168.1.10:80 weight=3; server 192.168.1.11:80; server 192.168.1.12:80 backup;}
server { location / { proxy_pass http://backend; }}Database
Section titled “Database”Q96: How do you manage MySQL/MariaDB?
Section titled “Q96: How do you manage MySQL/MariaDB?”Answer:
# Installapt install mariadb-server
# Secure installationmysql_secure_installation
# Connectmysql -u root -p
# Common commandsSHOW DATABASES;CREATE DATABASE dbname;USE dbname;SHOW TABLES;DESCRIBE tablename;
# Backupmysqldump -u root -p dbname > backup.sql
# Restoremysql -u root -p dbname < backup.sqlQ97: How do you configure PostgreSQL?
Section titled “Q97: How do you configure PostgreSQL?”Answer:
# Installapt install postgresql
# Connectsudo -u postgres psql
# Commands\list # list databases\dt # list tables\du # list users
# Create databaseCREATE DATABASE mydb;CREATE USER myuser WITH PASSWORD 'secret';GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
# Backuppg_dump -U user dbname > backup.sql
# Restorepsql -U user dbname < backup.sqlQ98: How do you optimize MySQL?
Section titled “Q98: How do you optimize MySQL?”Answer:
[mysqld]innodb_buffer_pool_size = 4Ginnodb_log_file_size = 1Gmax_connections = 500query_cache_size = 0table_open_cache = 4000slow_query_log = 1slow_query_log_file = /var/log/mysql/slow.loglong_query_time = 2
# Key parameters# innodb_buffer_pool - 70-80% of RAM# max_connections - based on expected concurrent connections# query_cache - deprecated in MySQL 8.0Q99: How do you configure database replication?
Section titled “Q99: How do you configure database replication?”Answer:
# Master config[mysqld]server-id = 1log_bin = /var/log/mysql/mysql-binbinlog_do_db = mydb
# Slave config[mysqld]server-id = 2relay-log = /var/log/mysql/mysql-relay-bin
# On masterGRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'password';FLUSH TABLES WITH READ LOCK;SHOW MASTER STATUS;
# On slaveCHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=xxx;START SLAVE;SHOW SLAVE STATUS\G;Q100: How do you secure databases?
Section titled “Q100: How do you secure databases?”Answer:
# MySQL security# 1. Remove anonymous usersDELETE FROM mysql.user WHERE User='';
# 2. Remove remote rootDELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1');
# 3. Create application userCREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strongpassword';GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'appuser'@'localhost';FLUSH PRIVILEGES;
# 4. Use SSL for connections# 5. Enable firewall for port 3306# 6. Regular backupsQuestions 101-200 continue with more advanced Linux topics…