Mastering Debian Linux. From Beginner to Advanced 2024
Mastering Debian Linux. From Beginner to Advanced 2024
Beginner to Advanced
Preface
Linux has long been a favorite among tech enthusiasts, developers, and
system administrators. Among the many distributions available, Debian
Linux stands out as one of the most stable, secure, and versatile operating
systems. Since its inception in 1993 by Ian Murdock, Debian has grown
into a cornerstone of the open-source world, influencing many other
distributions like Ubuntu. Debian's commitment to the ideals of free
software and its solid foundation make it a top choice for servers, desktops,
and embedded systems alike.
Why Debian?
Through this book, you will gain a strong understanding of how to:
While there are many excellent Linux resources available, this book focuses
specifically on Debian, addressing the unique aspects of the distribution and
its ecosystem. We take a hands-on approach, emphasizing real-world
applications and providing clear, detailed instructions. Whether you are
deploying Debian in a data center, on a desktop, or in the cloud, this book
will equip you with the knowledge and skills necessary to make the most of
this powerful and versatile operating system.
As you journey through this book, remember that learning Linux, and
Debian in particular, is not just about memorizing commands or configuring
servers—it's about joining a global community of users and contributors
who share a passion for free and open-source software. We hope this book
inspires you to explore Debian further and maybe even contribute back to
the project.
Acknowledgments
This book would not have been possible without the dedicated efforts of the
Debian development community. Their tireless work over the years has
made Debian one of the most respected and widely-used Linux distributions
in the world. We would also like to thank the many open-source developers
and enthusiasts who contribute to the broader Linux ecosystem. Lastly, we
are grateful to the readers who continue to support Linux and open-source
initiatives—this book is for you.
CloudMatrix s.r.o.
Table of Contents
Chapter Content
- Initial Setup
• Understanding Debian's
Configuration Files
• User and Group Management
• Introduction to Systemd
• Managing Services: Start, Stop,
Chapter 6: Services and Enable, and Disable
Daemons • Running Background Processes
• Automating Tasks with Cron and
Anacron
• Introduction to Desktop
Environments (GNOME, KDE,
XFCE)
Chapter 9: Desktop • Customizing the Debian Desktop
Environment on Debian • Installing and Using GUI-Based
Applications
• Configuring Printers and Other
Peripherals
• Introduction to Virtualization
(KVM, VirtualBox)
• Installing and Managing Virtual
Chapter 10: Virtualization and Machines on Debian
Containers • Using Docker and Podman for
Containerization
• Setting up and Managing LXC/LXD
Containers
• Setting Up a Development
Environment (IDE, Text Editors)
• Programming Languages on Debian
(Python, C, Java, etc.)
Chapter 12: Debian for
• Package Creation and Distribution
Developers
(Debian Package Creation)
• Version Control with Git on Debian
• Using Debian for Embedded
Systems
• Understanding Debian's
Development Cycle
• Contributing to Debian (Packages,
Code, Documentation)
Chapter 13: The Debian • The Debian Social Contract and
Community and Ecosystem Free Software Guidelines
• Working with the Debian Bug
Tracking System
• Finding Help: Mailing Lists,
Forums, and IRC
Linus (torvalds@kruuna.helsinki.fi)
PS. Yes - it's free of any minix code, and it has a multi-
threaded fs. It is NOT portable (uses 386 task switching
etc), and it probably never will support anything other than
AT-harddisks, as that's all I have :-(.
The initial release of Linux (version 0.01) was made available in September
1991. It was a bare-bones system with limited functionality, but it quickly
caught the attention of other programmers and enthusiasts. The open-source
nature of the project allowed developers from around the world to
contribute, leading to rapid improvements and expansions.
In 1992, Torvalds released version 0.12 under the GNU General Public
License (GPL), which ensured that the Linux kernel would remain free and
open-source. This decision was crucial in fostering a collaborative
development environment and aligning Linux with the broader free
software movement.
It's important to note that Linux is technically just the kernel – the core
component of an operating system that manages hardware resources and
provides essential services. To create a complete, usable operating system,
Linux is typically combined with the GNU operating system tools and
utilities developed by the Free Software Foundation.
This combination of the Linux kernel with GNU tools is often referred to as
GNU/Linux, although "Linux" is commonly used as shorthand for the entire
system.
Throughout the 1990s and early 2000s, Linux continued to evolve and gain
popularity. Major milestones included:
Today, Linux powers a vast array of devices and systems, from smartphones
and smart TVs to supercomputers and web servers. Its impact on the
technology landscape is immeasurable, and its continued development
serves as a testament to the power of open-source collaboration.
There are hundreds of Linux distributions available, each with its own
unique characteristics. Some of the most popular include:
1. Target Audience:
2. Release Cycle:
4. Init System:
Debian is renowned for its rock-solid stability. The Debian project follows a
conservative approach to package updates, thoroughly testing software
before including it in the stable release. This makes Debian an excellent
choice for servers and mission-critical systems where reliability is
paramount.
This flexibility allows users to choose the branch that best suits their needs.
The Debian project is known for its strong, global community of developers
and users. The project's democratic structure ensures that decisions are
made in the best interest of the community and the principles of free
software.
7. Basis for Many Other Distributions
8. Excellent Documentation
9. Long-Term Support
Debian Stable releases are supported for about 3 years, with some releases
receiving extended long-term support. This ensures that systems can remain
secure and stable for extended periods without requiring major upgrades.
Debian allows for a very minimal installation, giving users complete control
over which software is installed on their system. This is particularly useful
for creating lightweight systems or customized server installations.
The Debian Security Team actively works to identify and fix security
vulnerabilities, often providing patches quickly after issues are discovered.
Debian calls itself the "Universal Operating System" due to its versatility. It
can be used on desktop computers, servers, and even embedded devices.
15. Customizability
Debian provides a solid base system that can be customized to suit a wide
range of needs, from minimal server installations to full-featured desktop
environments.
Pre-installation Considerations
Before you begin the installation process, there are several important factors
to consider:
1. System Requirements:
Ensure your hardware meets the minimum requirements for Debian.
For a desktop system, this typically includes:
2 GHz dual-core processor
2 GB RAM (4 GB recommended)
10 GB hard drive space (20 GB recommended)
Graphics card and monitor capable of 1024x768 resolution
Download the Debian ISO image from the official website and create a
bootable USB drive or burn a DVD.
Decide how you want to partition your hard drive, especially if you're
dual-booting with another operating system.
When the Debian installer boots, you'll see several options. For most
users, "Graphical install" is recommended.
4. Configure Network:
Enter a name for your computer (hostname) and domain name (if
applicable).
Select your time zone and choose whether to use NTP for automatic
time synchronization.
8. Partition Disks:
After successfully installing Debian, there are several steps you should take
to set up and optimize your system:
Install any additional software you need. For example, to install the
Firefox web browser:
4. Set Up Firewall:
For full multimedia support, you may need to install additional codecs:
7. Set Up Backups:
This comprehensive guide should provide you with a solid foundation for
installing and setting up Debian Linux. As you progress, you'll find that
Debian's stability, extensive software repositories, and strong community
support make it an excellent choice for both beginners and experienced
Linux users alike.
Chapter 2: Getting Started with
Debian
Understanding the Debian File System Structure
The Debian file system structure follows the Filesystem Hierarchy Standard
(FHS), which provides a consistent and organized layout for directories and
files across Unix-like operating systems. Understanding this structure is
crucial for effective system administration and navigation.
The root directory is the top-level directory in the Debian file system
hierarchy. All other directories and files are contained within the root
directory. It is represented by a forward slash (/).
Key Directories
Important Files
7. cp: Copy
System Information
Text Processing
Network Commands
Process Management
27. ps: Process Status
Lists running processes.
Example: ps aux
28. kill: Terminate Process
Sends signals to processes, often used to terminate them.
Example: kill -9 1234
1. BIOS/UEFI Initialization:
2. Bootloader (GRUB):
3. Kernel Initialization:
The Linux kernel initializes hardware drivers and mounts the root file
system.
It starts the init process (systemd in Debian).
4. Systemd Initialization:
5. Service Startup:
6. Display Manager:
7. User Login:
1. Shutdown Command:
2. Systemd Shutdown:
sudo reboot
sudo poweroff
Understanding the system startup and shutdown processes, along with the
tools to control them, is essential for effective system administration and
troubleshooting in Debian.
APT Components
3. Install a Package:
4. Remove a Package:
1. Adding a Repository:
2. Enabling/Disabling Repositories:
Best Practices
1. Regular Updates: Run sudo apt update && sudo apt upgrade
regularly to keep the system up-to-date.
2. Verify Package Sources: Only add trusted repositories to avoid
security risks.
3. Backup Before Major Changes: Create system backups before
performing significant package operations.
4. Read Package Descriptions: Review package information before
installation to understand its purpose and requirements.
5. Use Virtual Environments: For development work, consider using
virtual environments to isolate package installations.
6. Clean Up Regularly: Use apt autoremove and apt clean to maintain
a clean system.
7. Check Dependencies: Before removing packages, check for
dependencies to avoid breaking other applications.
1. APT (Recommended):
3. Snap Packages:
4. Flatpak:
./configure
make
sudo make install
6. AppImage:
4. Downgrading Packages:
6. Cleaning Up:
1. Adding Repositories:
2. Removing Repositories:
1. Dependency Problems:
2. Package Conflicts:
3. Failed Installations:
Check system logs: journalctl -xe
Verify package integrity: sudo apt install --reinstall
package_name
4. Repository Issues:
4. Read Documentation:
1. /etc/fstab: File System Table, defines how disk partitions and other
block devices are mounted into the file system.
2. /etc/passwd: Stores essential information for each user account.
3. /etc/shadow: Contains encrypted passwords for user accounts.
4. /etc/group: Defines user groups and their members.
5. /etc/hostname: Specifies the system's hostname.
6. /etc/hosts: Maps hostnames to IP addresses.
7. /etc/resolv.conf: DNS resolver configuration file.
8. /etc/sudoers: Configures sudo access and permissions.
Lines beginning with # are comments and are ignored by the system.
Configuration options are typically specified in key=value or key
value format.
Some files use more complex formats, such as XML or INI-style
configurations.
1. Ansible
2. Puppet
3. Chef
4. Salt
These tools can help automate the process of configuring and maintaining
multiple systems consistently.
Group Accounts
This creates a user with a home directory (-m) and sets the login shell to
bash (-s).
Removing Users
To remove the user's home directory and mail spool as well, add the --
remove-home option:
# Lock
sudo passwd -l username
# Unlock
sudo passwd -u username
File Permissions
1. Owner permissions
2. Group permissions
3. Others permissions
Each set can have read (r), write (w), and execute (x) permissions.
In this example:
Changing Permissions
1. Symbolic notation:
2. Numeric notation:
chmod 644 file # Set rw-r--r-- permissions
chmod 755 file # Set rwxr-xr-x permissions
Changing Ownership
Special Permissions
To set an ACL:
To view ACLs:
getfacl file
Disk Partitioning
Partitioning Tools
# Commands:
# n - create new partition
# p - print partition table
# w - write changes and exit
File Systems
Temporary Mounting
sudo mount -a
df -h
Network Interfaces
Network interfaces are the connection points between your system and the
network. Common types include:
ip link show
or
ifconfig -a
IP Address Configuration
Static IP Configuration
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
auto eth0
iface eth0 inet dhcp
Network Manager
After installation, you can use the nmcli command-line tool or the
graphical interface to manage connections.
Hostname Configuration
1. Edit /etc/hostname:
new-hostname
2. Update /etc/hosts:
127.0.0.1 localhost
127.0.1.1 new-hostname
DNS Configuration
nameserver 8.8.8.8
nameserver 8.8.4.4
Firewall Configuration
Debian uses iptables for firewall functionality. For easier management,
you can use ufw (Uncomplicated Firewall):
1. Install ufw:
2. Enable ufw:
4. Check status:
traceroute google.com
ss -tuln
nmap 192.168.1.0/24
ntpq -p
IPv6 Configuration
1. Edit /etc/sysctl.conf:
# To disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
2. Apply changes:
sudo sysctl -p
Network Bonding
2. Edit /etc/network/interfaces:
auto bond0
iface bond0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
bond-slaves eth0 eth1
bond-mode active-backup
bond-miimon 100
bond-primary eth0
3. Restart networking:
1. Install OpenVPN:
4. Enable autostart:
PermitRootLogin no
Types of Dependencies
Resolving Dependencies
Modern package managers like APT (Advanced Package Tool) for Debian-
based systems or YUM (Yellowdog Updater, Modified) for Red Hat-based
systems automatically handle most dependency resolutions. However,
understanding the process can help in troubleshooting complex scenarios.
Handling Conflicts
Benefits of PPAs
Adding a PPA
Removing a PPA
To remove a PPA, you can use the --remove flag with add-apt-
repository or use the ppa-purge tool:
External repositories are third-party sources for packages that are not
included in the official distribution repositories.
wget https://example.com/software-1.2.3.tar.gz
tar -xzvf software-1.2.3.tar.gz
cd software-1.2.3
2. Checking Prerequisites
./configure
This script checks your system for required components and creates a
Makefile tailored to your environment. You can pass options to
configure to customize the build:
4. Compiling
make
This command reads the Makefile and compiles the source code into
binary executables.
5. Installing
This copies the compiled files to their appropriate locations in the system.
Types of Updates
Upgrading Packages
For a more aggressive upgrade that can add or remove packages to satisfy
dependencies:
Automated Updates
Applying Updates
Automated Updates
Red Hat-based systems use the dnf-automatic package for automated
updates:
sudo do-release-upgrade
For servers, you might want to use the -d flag to upgrade to the latest
supported release:
sudo do-release-upgrade -d
Post-Upgrade Tasks
1. Check System Status: Verify that all services are running correctly.
2. Update Configuration Files: Review and update any custom
configuration files.
3. Reinstall Third-Party Software: Some third-party software may need
to be reinstalled or reconfigured.
4. Clean Up: Remove old kernels and unnecessary packages:
Conclusion
Advanced package management is a critical skill for Linux system
administrators. Understanding how to handle dependencies, work with
various repositories, compile software from source, and manage system
updates and upgrades allows for more efficient and secure system
administration.
The principle of least privilege states that users, processes, and applications
should only have the minimum level of access necessary to perform their
tasks. This principle helps limit the potential damage that can occur if a user
account or process is compromised.
Defense in Depth
Keep It Simple
Effective monitoring and logging are essential for detecting and responding
to security incidents. Proper logging can also help with forensic analysis
after an incident has occurred.
Regular Backups
While not strictly a security measure, regular backups are crucial for
recovering from security incidents, such as ransomware attacks or data
corruption.
Installing UFW
To install UFW on Debian, use the following command:
1. Enable UFW:
6. Delete a rule:
Configuring UFW
IPTables
sudo iptables -L
Here's a basic IPTables configuration that allows SSH and HTTP traffic
while blocking all other incoming connections:
# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Log dropped packets
iptables -A INPUT -j LOG --log-prefix "IPTables Dropped: " -
-log-level 7
Key-based Authentication
ssh-copy-id user@server
Set PasswordAuthentication no
Changing the default SSH port can help reduce automated attacks. To
change the SSH port:
2. Find the line #Port 22 and change it to a non-standard port, e.g., Port
2222
3. Restart the SSH service:
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-
group-exchange-sha256
3. Limit SSH protocol version:
Installing Sudo
Sudo is usually pre-installed on Debian systems. If it's not, you can install it
with:
su -
apt install sudo
Configuring Sudo
sudo visudo
Here's a basic sudo configuration that allows members of the sudo group to
execute any command:
Passwordless Sudo
To allow a user to use sudo without entering a password (use with caution):
SELinux
Installing SELinux
Enabling SELinux
sudo update-grub
SELinux Modes
SELinux Contexts
ls -Z /path/to/file
SELinux Booleans
To change a boolean:
AppArmor
Installing AppArmor
Enabling AppArmor
sudo update-grub
AppArmor Modes
sudo aa-status
sudo aa-status
sudo aa-logprof
Conclusion
Securing a Debian system involves implementing multiple layers of
protection, from basic security principles to advanced access control
systems like SELinux and AppArmor. By following the practices outlined
in this chapter, you can significantly enhance the security of your Debian
system.
Systemd Units
Here are some essential systemd commands using the systemctl utility:
Starting a Service
This command will attempt to start the service immediately. If the service is
already running, the command will have no effect.
Stopping a Service
This command will attempt to stop the service gracefully. If the service is
not running, the command will have no effect.
Restarting a Service
To restart a service (stop and then start), use the following command:
This is useful when you've made configuration changes and want to apply
them without manually stopping and starting the service.
Reloading a Service
Enabling a Service
This command creates the necessary symlinks to start the service at boot
time, but it does not start the service immediately.
Disabling a Service
For example, to disable the Apache web server from starting at boot:
sudo systemctl disable apache2
This removes the symlinks that cause the service to start at boot, but it does
not stop the service if it's currently running.
Masking is more extreme than disabling and should be used with caution.
To start a process in the background from the command line, you can use
the & symbol at the end of the command:
command &
For example:
long_running_script.sh &
This starts the script and returns control to the terminal immediately, with
the process running in the background.
Use the jobs command to list current background jobs in the current shell
session:
jobs
Use the fg command followed by the job number (as shown by jobs ):
fg %1
3. Sending a Foreground Process to the Background:
Press Ctrl+Z to suspend the current foreground process, then use the bg
command to continue it in the background:
bg
kill %1
or
kill 1234
Nohup Command
Basic usage:
screen
# Run your commands
# Press Ctrl+A, then D to detach
screen -r # to reattach
Basic usage:
tmux
# Run your commands
# Press Ctrl+B, then D to detach
tmux attach # to reattach
[Unit]
Description=My Custom Application
[Service]
ExecStart=/path/to/my/app
[Install]
WantedBy=default.target
Cron
Cron is a time-based job scheduler in Unix-like operating systems. It
enables users to schedule jobs (commands or shell scripts) to run
periodically at fixed times, dates, or intervals.
Cron Daemon
The cron daemon ( crond ) runs in the background and checks for scheduled
tasks every minute. It reads the crontab files to determine which commands
to execute.
Crontab Files
Crontab Syntax
* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └─── Day of the week (0 - 7) (Sunday = 0 or 7)
│ │ │ └────── Month (1 - 12)
│ │ └───────── Day of the month (1 - 31)
│ └──────────── Hour (0 - 23)
└─────────────── Minute (0 - 59)
Crontab Commands
30 3 * * * /path/to/script.sh
*/15 * * * * /path/to/command
0 9 * * 1-5 /path/to/weekday-job
4. Run a monthly job on the first day of the month:
0 0 1 * * /path/to/monthly-job
/etc/cron.daily/
/etc/cron.hourly/
/etc/cron.weekly/
/etc/cron.monthly/
Scripts placed in these directories will run at the specified intervals without
needing to edit crontab files.
Anacron
Anacron Configuration
The main configuration file for anacron is /etc/anacrontab . Its format is
similar to crontab but with some differences:
1 5 daily-backup /path/to/backup-script.sh
7 10 weekly-update /path/to/update-script.sh
1. Use Absolute Paths: Always use full paths to commands and scripts
in cron and anacron jobs.
2. Redirect Output: Redirect stdout and stderr to log files or /dev/null
to prevent email notifications for every job run.
3. Set a Proper PATH: Set the PATH variable at the beginning of your
crontab or in the scripts you run.
4. Use Comments: Add comments to explain what each job does,
especially in shared environments.
5. Test Your Jobs: Always test your cron and anacron jobs thoroughly
before setting them to run automatically.
6. Monitor Job Execution: Regularly check logs to ensure your
automated tasks are running as expected.
7. Use Appropriate Scheduling: Don't schedule resource-intensive tasks
during peak system usage times.
8. Security Considerations: Be cautious about what commands you run
automatically, especially if they require elevated privileges.
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/us
r/bin
2. Special Time Strings: Cron supports special time strings like @reboot,
@yearly, @monthly, @weekly, @daily, and @hourly.
3. Cron Job Monitoring: Tools like Cronitor or Healthchecks.io can be
used to monitor the execution of critical cron jobs.
4. Cron Job Management Tools: Consider using tools like fcron or
cronie for more advanced cron job management features.
Conclusion
As with all powerful tools, it's important to use these features responsibly,
considering system resources, security implications, and the potential
impact on other users or processes. Regular monitoring, logging, and
maintenance of automated tasks and services are essential practices for
maintaining a healthy and efficient Linux system.
Chapter 7: Networking in Debian
Networking is a crucial aspect of any modern operating system, and Debian
is no exception. This chapter will delve into the various aspects of
networking in Debian, from basic configuration to advanced
troubleshooting techniques. We'll cover how to set up network interfaces,
configure static IPs and DNS, troubleshoot network issues, and even set up
basic web servers and secure remote access protocols.
You can view your system's network interfaces using the ip link
command:
ip link show
This file is the main configuration file for network interfaces in Debian.
Here's an example of a basic configuration:
DHCP Configuration
Static IP Configuration
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
auto wlan0
iface wlan0 inet dhcp
wpa-ssid YourNetworkName
wpa-psk YourNetworkPassword
After making changes to the network configuration, you need to restart the
networking service or reboot the system for the changes to take effect:
sudo systemctl restart networking
or
sudo reboot
Configuring a Static IP
To set up a static IP, edit the /etc/network/interfaces file and add the
following configuration for your network interface:
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
In this example:
Configuring DNS
Using /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
Network Troubleshooting
Network issues can be frustrating, but Debian provides several tools to help
diagnose and resolve these problems.
Ping
ping google.com
This command sends ICMP echo request packets to the specified host and
waits for a reply. If successful, you'll see a series of responses with round-
trip times.
Traceroute
The traceroute command shows the path that packets take to reach a
destination, helping you identify where network issues might be occurring.
traceroute google.com
This command will display a list of routers (hops) that the packets traverse
to reach the destination.
Netstat
netstat -tuln
This command shows all active TCP and UDP connections, along with the
ports they're using.
IP Command
To view IP addresses:
ip addr show
ip route show
Checking DNS Resolution
To check if DNS resolution is working correctly, you can use the nslookup
or dig commands:
nslookup google.com
or
dig google.com
These commands will show you the IP addresses associated with the
domain name.
ip link show
This command will display all network interfaces and their current state
(UP or DOWN).
Firewall Troubleshooting
If you're having issues with network connectivity, it's worth checking if the
firewall is blocking traffic. In Debian, the default firewall is iptables . You
can list the current firewall rules with:
sudo iptables -L
If you're using ufw (Uncomplicated Firewall), you can check its status
with:
To see which network services are running and listening for connections:
sudo ss -tuln
This command shows all TCP and UDP ports that are in a listening state.
Logging
You can use the tail command to view the most recent entries in these log
files:
Apache is one of the most widely used web servers and is included in the
Debian repositories.
Installation
To install Apache:
Basic Configuration
The main configuration file for Apache is /etc/apache2/apache2.conf .
However, for most basic setups, you won't need to modify this file directly.
<VirtualHost *:80>
ServerName mysite.com
ServerAlias www.mysite.com
DocumentRoot /var/www/mysite
ErrorLog ${APACHE_LOG_DIR}/mysite_error.log
CustomLog ${APACHE_LOG_DIR}/mysite_access.log combined
</VirtualHost>
3. Create the document root directory:
5. Reload Apache:
Testing Apache
After installation, Apache should start automatically. You can check its
status with:
Nginx is known for its high performance and low resource usage, making it
a popular choice for web servers.
Installation
To install Nginx:
Basic Configuration
server {
listen 80;
server_name mysite.com www.mysite.com;
root /var/www/mysite;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
sudo ln -s /etc/nginx/sites-available/mysite
/etc/nginx/sites-enabled/
Testing Nginx
After installation, Nginx should start automatically. You can check its status
with:
Setting up SFTP
Using SFTP
sftp username@remote_host
Securing SFTP
SSH is a secure protocol used for remote server administration and secure
data communication.
Setting up SSH
As with SFTP, SSH is provided by the OpenSSH server. If it's not already
installed:
Using SSH
ssh username@remote_host
Replace username with your username on the remote server and
remote_host with the server's IP address or domain name.
ssh-copy-id username@remote_host
ssh username@remote_host
Securing SSH
Conclusion
Networking is a vast and complex topic, but understanding the basics of
network configuration, troubleshooting, and secure communication in
Debian is essential for effective system administration. This chapter has
covered the fundamental aspects of networking in Debian, from configuring
network interfaces and setting up static IPs to troubleshooting network
issues and setting up basic web servers.
We've also introduced secure protocols like SFTP and SSH, which are
crucial for remote server management and secure file transfers. By
mastering these concepts and tools, you'll be well-equipped to manage
Debian systems in networked environments effectively.
LAMP Stack
The LAMP stack is a traditional and widely used web server configuration.
Here's how to set it up on Debian:
sudo mysql_secure_installation
LEMP Stack
The LEMP stack replaces Apache with Nginx, which is known for its high
performance and low resource usage. Here's how to set up a LEMP stack on
Debian:
sudo mysql_secure_installation
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
Database Management
(MySQL/MariaDB/PostgreSQL)
Databases are essential for storing and managing data in many applications.
Let's explore how to work with popular database systems on Debian.
MySQL/MariaDB
1. Connect to MySQL/MariaDB:
sudo mysql
4. Back up a database:
5. Restore a database:
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 150
PostgreSQL
1. Install PostgreSQL:
5. Back up a database:
6. Restore a database:
shared_buffers = 256MB
effective_cache_size = 768MB
work_mem = 4MB
maintenance_work_mem = 64MB
2. Configure Bind9:
options {
directory "/var/cache/bind";
recursion yes;
allow-recursion { trusted; };
listen-on { 192.168.1.100; };
allow-transfer { none; };
forwarders {
8.8.8.8;
8.8.4.4;
};
};
$TTL 604800
@ IN SOA ns1.example.com. admin.example.com.
(
2 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
;
@ IN NS ns1.example.com.
@ IN A 192.168.1.100
www IN A 192.168.1.100
Edit /etc/bind/named.conf.local :
zone "example.com" {
type master;
file "/etc/bind/db.example.com";
};
5. Restart Bind9:
1. Install Postfix:
sudo apt install postfix
2. Configure Postfix:
myhostname = mail.example.com
mydestination = $myhostname, example.com,
localhost.$mydomain, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
home_mailbox = Maildir/
mailbox_command =
4. Restart Postfix:
1. Install Dovecot:
2. Configure Dovecot:
Edit /etc/dovecot/conf.d/10-auth.conf :
disable_plaintext_auth = no
auth_mechanisms = plain login
Edit /etc/dovecot/conf.d/10-mail.conf :
mail_location = maildir:~/Maildir
5. Restart Dovecot:
Edit /etc/postfix/main.cf :
smtpd_tls_cert_file=/etc/ssl/certs/mail.crt
smtpd_tls_key_file=/etc/ssl/private/mail.key
smtpd_use_tls=yes
smtpd_tls_auth_only = yes
Edit /etc/dovecot/conf.d/10-ssl.conf :
ssl = required
ssl_cert = </etc/ssl/certs/mail.crt
ssl_key = </etc/ssl/private/mail.key
DigitalOcean
1. Sign up for a Google Cloud Platform account if you don't have one.
2. Navigate to the Compute Engine section and click "Create Instance".
3. Choose a name for your instance.
4. Select a region and zone for your instance.
5. Choose the machine type based on your requirements (e.g., e2-micro
for a small server).
6. In the "Boot disk" section, click "Change" and select Debian as the
operating system.
7. Configure firewall rules to allow HTTP and HTTPS traffic if needed.
8. Click "Create" to launch the instance.
9. Once the instance is running, you can connect to it using the Google
Cloud Console or SSH:
Post-Deployment Steps
After deploying your Debian VPS on any cloud platform, it's important to
perform some initial setup and security measures:
Edit /etc/ssh/sshd_config :
PermitRootLogin no
PasswordAuthentication no
By following these steps, you'll have a secure Debian VPS ready for further
configuration and application deployment.
Conclusion
In this chapter, we've covered essential topics for working with Debian on
servers, including setting up web servers, managing databases, configuring
DNS, setting up email servers, and deploying Debian VPS instances on
cloud platforms. These skills provide a solid foundation for managing and
maintaining Debian-based server environments.
As you continue to work with Debian servers, remember to stay updated on
security best practices, regularly update your systems, and monitor your
servers for performance and potential issues. With its stability and extensive
package ecosystem, Debian is an excellent choice for a wide range of server
applications and use cases.
Chapter 9: Desktop Environment
on Debian
Introduction to Desktop Environments
A desktop environment is a collection of software that provides a graphical
user interface (GUI) for interacting with your computer. It typically
includes a window manager, file manager, panel or dock, and various other
utilities and applications. Debian offers several popular desktop
environments, with GNOME, KDE, and XFCE being among the most
widely used.
GNOME
Pros of GNOME:
Cons of GNOME:
KDE Plasma
Plasma Desktop: The main interface, including the panel and widgets
KWin: The window manager with extensive effects and tiling
capabilities
Activities: A way to organize different workspaces for various tasks
KDE Connect: Integration with mobile devices
Pros of XFCE:
Cons of XFCE:
Appearance
2. Icons: Install and apply different icon sets to give your desktop a fresh
look.
Performance Tweaks
Finding Applications
Launch Synaptic from your application menu and use the search function to
find software.
2. GNOME Software Center: The default software manager for
GNOME.
Search for applications by name or category, and click "Install" to add them
to your system.
Installing Applications
1. Web Browsers:
2. Office Suite:
3. Image Editing:
4. Media Players:
5. Communication:
6. Development Tools:
Using Applications
1. Launching: Most applications can be launched from the application
menu or dock.
2. Updating: GUI applications are updated along with system updates.
You can also update individual applications through the Software
Center or using:
4. Creating shortcuts:
Printers
1. CUPS (Common Unix Printing System):
CUPS is the standard print server for Debian. It's usually pre-installed, but
if not:
2. Adding a printer:
3. Printer drivers:
Many printers work out of the box, but some may require additional drivers:
Scanners
2. Adding a scanner:
scanimage -L
3. Scanning software:
4. Troubleshooting:
1. Automatic mounting:
2. Manual mounting:
Replace sdX1 with the appropriate device identifier (use lsblk to find it).
3. Unmounting:
4. Formatting:
Bluetooth Devices
1. Enabling Bluetooth:
2. Pairing devices:
bluetoothctl
[bluetooth]# scan on
[bluetooth]# pair XX:XX:XX:XX:XX:XX
[bluetooth]# connect XX:XX:XX:XX:XX:XX
3. Troubleshooting:
1. Nvidia drivers:
2. AMD drivers:
3. Intel drivers:
Webcams
1. Testing webcam:
sudo apt install v4l-utils
v4l2-ctl --list-devices
2. Webcam applications:
Audio Devices
1. PulseAudio:
The default audio server for Debian. It's usually pre-installed, but if not:
2. Audio controls:
Use your desktop environment's volume control
Or use command-line tools:
3. Troubleshooting:
Restart PulseAudio:
aplay -l
arecord -l
Wacom Tablets
1. Driver installation:
3. Testing:
1. Hardware information:
2. Device manager:
3. Udev rules:
lsmod
Load a module:
Unload a module:
What is Virtualization?
Benefits of Virtualization
VirtualBox
Learning
Steeper Gentler
Curve
Prerequisites
Before installing KVM, ensure that your system meets the following
requirements:
You can create virtual machines using either the command-line interface or
the graphical virt-manager tool. We'll cover both methods:
1. Launch virt-manager:
virt-manager
To start a VM:
To stop a VM:
Connecting to VM Console
To create a snapshot:
To list snapshots:
Introduction to Docker
2. Install prerequisites:
FROM debian:buster-slim
RUN apt-get update && apt-get install -y nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Introduction to Podman
Daemonless architecture
Rootless containers
Pod support (groups of containers)
Compatible with Docker images and registries
. /etc/os-release
echo "deb
https://download.opensuse.org/repositories/devel:/kubic:/lib
containers:/stable/Debian_${VERSION_ID}/ /" | sudo tee
/etc/apt/sources.list.d/devel:kubic:libcontainers:stable.lis
t
curl -L
"https://download.opensuse.org/repositories/devel:/kubic:/li
bcontainers:/stable/Debian_${VERSION_ID}/Release.key" | sudo
apt-key add -
Client-server
Architecture Daemonless
(requires daemon)
Introduction to LXC/LXD
2. Install LXD:
4. Initialize LXD:
Creating a Container
To create a snapshot:
LXD Clustering
lxd init
1. Regular Updates: Keep both the host system and containers updated.
2. Resource Monitoring: Use tools like lxc info to monitor container
resource usage.
3. Security: Use unprivileged containers when possible and apply
security profiles.
4. Backup Strategy: Implement regular backups of your containers and
their data.
5. Network Isolation: Use separate bridges or VLANs for different
container groups.
Conclusion
Virtualization and containerization technologies offer powerful tools for
managing and deploying applications and systems. Each technology -
KVM, VirtualBox, Docker, Podman, and LXC/LXD - has its strengths and
use cases.
KVM is ideal for full virtualization needs, especially in Linux
environments.
VirtualBox offers a user-friendly approach to virtualization, suitable
for desktop users and small-scale deployments.
Docker provides a standardized way to package and deploy
applications, with a large ecosystem of pre-built images.
Podman offers similar functionality to Docker but with added security
benefits and no daemon requirement.
LXC/LXD bridges the gap between containers and full VMs, offering
lightweight, flexible system containers.
htop
To install htop:
To run htop:
htop
Key features of htop:
F1: Help
F2: Setup (customize display options)
F3: Search
F4: Filter
F5: Tree view
F6: Sort by column
F9: Kill process
F10: Quit
iostat
To install iostat:
iostat
Example usage:
iostat -x 5 3
2. free: Displays the amount of free and used memory in the system.
free -h
df -h
du -sh /path/to/directory
2. Kernel panic:
journalctl -b
dmesg | less
systemd-analyze blame
Kernel-related Troubleshooting
uname -r
2. Listing installed kernels:
Log Rotation
Log rotation is the process of archiving and compressing old log files to
prevent them from consuming too much disk space. Debian uses the
logrotate utility to manage log rotation.
cat /etc/logrotate.conf
tail -f /var/log/syslog
For centralized log management, you can configure your Debian system to
send logs to a remote syslog server.
*.* @remote_server_ip:514
auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, syslog, user,
uucp, local0 through local7
Rsyslog Configuration
Debian uses rsyslog as its default syslog daemon. The main configuration
file is /etc/rsyslog.conf .
Example rule:
auth,authpriv.* /var/log/auth.log
CPU Optimization
Install cpufrequtils:
2. Process niceness: Adjust process priority using the nice and renice
commands.
nice -n 10 command_to_run
sudo renice -n 10 -p process_id
3. CPU affinity: Bind processes to specific CPU cores using taskset.
Memory Optimization
Network Optimization
3. Apply changes:
sudo sysctl -p
Application-specific Optimization
Backup Strategies
Backup Tools
Example usage:
Example usage:
Example usage:
Example usage:
Automating Backups
0 2 * * * /path/to/backup_script.sh
2. Systemd timers: Use systemd timers for more flexible scheduling
options.
[Unit]
Description=Daily backup timer
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
[Service]
ExecStart=/path/to/backup_script.sh
[Install]
WantedBy=multi-user.target
Testing Backups
1. Live system rescue: Boot from a live USB or CD to access and repair
a non-booting system.
2. Chroot environment: Use chroot to access and repair a damaged
system from a live environment.
By implementing these backup and recovery strategies, you can ensure that
your Debian system and its data are protected against various failure
scenarios, minimizing downtime and data loss in case of emergencies.
IDEs
Eclipse
NetBeans
NetBeans offers excellent support for Java development and provides tools
for web and mobile application development.
Visual Studio Code (VS Code) is a lightweight, yet powerful, source code
editor developed by Microsoft. It has gained significant popularity among
developers due to its extensibility and performance.
Text Editors
For developers who prefer a more lightweight approach or need to edit files
quickly, Debian offers several powerful text editors.
Vim
Vim is a highly configurable text editor built to enable efficient text editing.
It's known for its modal editing and extensive plugin ecosystem.
Emacs
Emacs is an extensible, customizable text editor. It's known for its powerful
editing capabilities and the ability to extend its functionality using Emacs
Lisp.
Sublime Text is a sophisticated text editor for code, markup, and prose.
While it's not open-source, it offers a free evaluation version.
After installing your preferred IDE or text editor, consider the following
steps to optimize your development environment:
Python
This command installs Python 3 and pip, the package installer for Python.
To create a virtual environment for Python development:
C/C++
C and C++ are powerful, low-level programming languages widely used in
system programming, game development, and performance-critical
applications.
This command installs gcc, g++, and other essential build tools.
Java
JavaScript (Node.js)
Ruby
Go
To install Go on Debian:
1. Download the latest Go binary release for Linux from the official Go
website.
2. Extract the archive to /usr/local:
export PATH=$PATH:/usr/local/go/bin
Rust
This command downloads and runs the Rust installation script, which
installs the latest stable version of Rust.
1. Prepare the source code: Organize your application's source code and
ensure it builds correctly.
2. Create the package directory structure:
myapp-1.0/
├── debian/
│ ├── changelog
│ ├── compat
│ ├── control
│ ├── copyright
│ ├── rules
│ └── source/
│ └── format
└── [application files and directories]
3. Create the debian/control file: This file contains package metadata
and dependencies.
Example:
Source: myapp
Section: utils
Priority: optional
Maintainer: Your Name <your.email@example.com>
Build-Depends: debhelper (>= 9)
Standards-Version: 3.9.8
Package: myapp
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: Short description of myapp
Long description of myapp that can span multiple lines.
It should provide more detailed information about the
package and its functionality.
Example:
* Initial release.
-- Your Name <your.email@example.com> Wed, 01 Jan 2023
12:00:00 +0000
Example:
#!/usr/bin/make -f
%:
dh $@
7. Build the package: Use the following command in the package's root
directory:
8. Test the package: Install the generated .deb file on a test system to
ensure it works correctly:
Once you've created your Debian package, you can distribute it through
various channels:
Installing Git
Configuring Git
1. Initialize a repository:
git init
3. Commit changes:
git status
5. View commit history:
git log
1. Clone a repository:
2. Switch to a branch:
4. Merge branches:
Several Git hosting services are available for storing and collaborating on
Git repositories:
1. GitHub: One of the most popular Git hosting platforms, offering both
public and private repositories.
2. GitLab: An open-source Git repository manager that can be self-
hosted or used as a cloud service.
3. Bitbucket: Offers Git and Mercurial repository hosting, with a focus
on team collaboration.
Cross-Compilation Tools
Cross-compilation allows you to build code for a target architecture
different from your host system. Debian provides cross-compilation tools
for various architectures.
Yocto Project
The Yocto Project is an open-source collaboration project that provides
templates, tools, and methods to create custom Linux-based systems for
embedded products.
cd poky
source oe-init-build-env
Security is crucial for embedded systems. Debian provides several tools for
enhancing embedded system security:
Unstable (Sid)
Testing
Freeze
A period before a new Stable release when focus shifts to bug fixing
No new features are added during this time
Only critical bug fixes and security updates are allowed
Stable
Old Stable
Debian uses characters from the Toy Story movies as codenames for its
releases:
Stable releases are named after Toy Story characters (e.g., Buster,
Bullseye)
The Testing branch is always named after the next planned Stable
release
Unstable is always called "Sid"
Release Timeframe
Package Maintenance
Code Contributions
Debian Installer
Package management tools (APT, dpkg)
Debian-specific utilities and scripts
Debian website and infrastructure tools
Documentation
Types of Documentation
Translation
Debian aims to be accessible to users worldwide, making translation a vital
contribution area.
Translation Process
Quality Assurance
QA Activities
Ways to Contribute
All software in the main distribution must comply with the DFSG
Debian will not make the system depend on non-free software
The needs of users and the free software community guide Debian's
decisions
Debian strives to create a robust, high-quality operating system
The Debian Free Software Guidelines are a set of criteria that Debian uses
to determine if a software package can be included in the main distribution.
These guidelines are an integral part of the Social Contract and serve as a
definition of "free software" in the context of Debian.
1. Free Redistribution
The license must allow free redistribution of the software
This includes selling or giving away the software as part of a larger
distribution
2. Source Code
The program must include source code and allow distribution in source
code as well as compiled form
If the product is distributed without source code, there must be a well-
publicized means of obtaining the source code
3. Derived Works
The license must allow modifications and derived works, and must
allow them to be distributed under the same terms as the original
software
The license must not restrict anyone from making use of the program
in a specific field of endeavor (e.g., business or genetic research)
7. Distribution of License
The rights attached to the program must apply to all to whom the
program is redistributed without the need for execution of an
additional license
8. License Must Not Be Specific to Debian
The rights attached to the program must not depend on the program
being part of a Debian system
The Social Contract and DFSG have had a significant impact not only on
Debian but on the broader free software community:
These ongoing discussions help to keep the Debian project true to its
principles while adapting to changing technological landscapes.
The Debian BTS is a public, email-based system that tracks bugs and
requests for improvement in Debian packages. Key features include:
Reporting a Bug
Reporting bugs is an important way for users to contribute to Debian's
quality. Here's how to report a bug effectively:
1. Prepare Information
3. Manual Reporting
Critical: Affects the whole system, causes data loss, or poses security
risks
Grave: Makes the package unusable or causes severe data loss
Serious: Violates Debian policy or makes the package unsuitable for
release
Important: Major problems that don't render the package completely
unusable
Normal: Default severity for most bugs
Minor: Minor issues that don't affect the package's usefulness
Wishlist: Suggestions for new features or improvements
Before reporting a new bug, it's important to check if it's already been
reported:
Tagging Bugs
Closing Bugs
Reopening Bugs
Email bugnumber-reopen@bugs.debian.org
Provide information on why the bug should be reopened
Subscribing to Bugs
Mailing Lists
Mailing lists are the primary means of communication within the Debian
community. They cover a wide range of topics and are suitable for both
users and developers.
1. Subscribing:
Visit lists.debian.org
Choose the appropriate list and follow subscription instructions
2. Posting:
3. Etiquette:
4. Searching Archives:
Forums
While mailing lists are the traditional form of communication, web forums
provide a more accessible platform for many users.
IRC provides real-time chat for immediate help and discussions. Debian
maintains several official channels on the OFTC network.
5. Use Pastebin: For long outputs, use a pastebin service and share the
link
6. Stay in the Channel: IRC is asynchronous; answers may come hours
later
7. Respect Channel Rules: Each channel may have specific guidelines
Documentation
Q&A Websites
Stack Exchange: The Unix & Linux Stack Exchange has many
Debian-related questions
Ask Debian: A community-driven Q&A site specifically for Debian
Social Media
1. Do Your Research:
Choose the right mailing list, forum, or IRC channel for your question
Avoid cross-posting across multiple channels
6. Keep Learning:
Debian on Raspberry Pi
The Raspberry Pi is a series of small single-board computers developed by
the Raspberry Pi Foundation. It has become immensely popular for
educational purposes, hobbyist projects, and even some industrial
applications. Debian is one of the primary operating systems supported on
Raspberry Pi devices.
The installation process for Debian on other ARM systems can vary
depending on the specific hardware. Generally, the steps involve:
Always refer to the documentation for your specific ARM device for
detailed installation instructions.
Challenges and Considerations
ARM64 Servers
1. Download the Debian ARM64 netinst ISO from the official Debian
website.
2. Create a bootable USB drive or use a network boot method supported
by your server.
3. Boot the server from the installation media and follow the standard
Debian installation process.
4. During installation, ensure you select the appropriate kernel and
bootloader options for your specific ARM64 hardware.
POWER9 Servers
5. Bootloader configuration:
Set up the bootloader (e.g., U-Boot) to load the kernel and root
filesystem.
6. Image creation:
Create a bootable image that includes the bootloader, kernel, and root
filesystem.
3. IoT gateway:
4. Network appliance:
Conclusion
Debian's support for non-x86 architectures, including ARM, ARM64,
POWER9, and various embedded platforms, showcases its versatility and
adaptability. Whether you're working with a Raspberry Pi for a hobby
project, deploying ARM64 or POWER9 servers for enterprise workloads,
or developing custom embedded systems, Debian provides a robust and
flexible foundation.