Linux Services, systemd, SSH, Cron Jobs and Logs

DevOps and Cloud Engineering: Complete Course from Beginner to Advanced · Linux Fundamentals · 9 min read · Updated

A service that stays up

  1. When the machine boots, systemd starts every enabled service.
  2. Your service starts from its unit file, running as the user you chose.
  3. If it crashes, systemd restarts it after the delay set by Restart and RestartSec.
  4. Every start and every message is recorded. journalctl -u shows the story.

A web server, a database or your Node application should start by itself when the machine boots, restart if it crashes, and run without anyone logged in. On modern Linux, a program called systemd looks after that. In this lesson you will learn how to control services, how to log in to a remote server safely with SSH keys, how to schedule repeating jobs with cron, and where to read the logs when something goes wrong. These four skills are what turn a Linux machine into a server you can trust.

Why do we need it?

Real applications must start at boot, restart after a crash and run when nobody is logged in. SSH lets you reach servers safely, cron runs repeating jobs, and logs tell you what happened when something goes wrong.

A real-life example

A service is like a shop that opens by itself every morning and a manager (systemd) who reopens it if the door jams. SSH is the key to the staff entrance, and the key is a card that only you hold. Cron is an alarm clock that rings tasks. Logs are the shop diary you read when something odd happened overnight.

Services and systemd

systemd is the first process on most modern distributions, and it starts and watches all the services. You control it with the systemctl command.

systemctl status nginx          # is it running? recent log lines
sudo systemctl start nginx       # start now
sudo systemctl stop nginx        # stop now
sudo systemctl restart nginx     # stop then start
sudo systemctl reload nginx      # re-read config without dropping connections (if supported)
sudo systemctl enable nginx      # start at every boot
sudo systemctl disable nginx     # do not start at boot
systemctl is-active nginx        # prints active or inactive

Two ideas are separate: start means run it now, and enable means run it at boot. Beginners often do one and forget the other. enable --now does both together.

Writing your own service

To run your own program as a service, you describe it in a unit file. Here is a unit for a Node application. It runs as a normal user, restarts if it crashes, and reads settings from a file that only the owner can see.

# /etc/systemd/system/jobtracker.service
[Unit]
Description=Job Tracker API
After=network.target

[Service]
Type=simple
User=deploy
WorkingDirectory=/opt/jobtracker
EnvironmentFile=/etc/jobtracker.env
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=3

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload            # tell systemd about the new file
sudo systemctl enable --now jobtracker
systemctl status jobtracker
journalctl -u jobtracker -f              # follow its logs

Keep passwords and keys in the EnvironmentFile, not in the unit file, and set that file to mode 600 so only its owner can read it.

SSH: logging in to a remote server

SSH gives you a secure terminal on another machine. Passwords can be guessed, so servers should use key pairs. A key pair has a private key, which stays on your computer and is never shared, and a public key, which you place on the server. The server can then check that you hold the private key without it ever travelling over the network.

ssh-keygen -t ed25519 -C "asha laptop"      # creates ~/.ssh/id_ed25519 and .pub
ssh-copy-id deploy@203.0.113.10              # puts the public key on the server
ssh deploy@203.0.113.10                      # log in with the key
chmod 600 ~/.ssh/id_ed25519                  # the private key must be private

The address 203.0.113.10 is a documentation example, not a real server. A short file called ~/.ssh/config saves typing, for example a block with Host jobs, HostName 203.0.113.10, User deploy and IdentityFile ~/.ssh/id_ed25519, after which ssh jobs is enough. On the server, hardening usually means turning off password login (PasswordAuthentication no) and root login (PermitRootLogin no) in /etc/ssh/sshd_config, then reloading the ssh service. Before you close your current session, open a second one and check that you can still log in, so that a typing mistake does not lock you out.

Cron jobs

Cron runs commands on a schedule. You edit your list of jobs with crontab -e. Each line has five time fields, then the command: minute, hour, day of month, month, day of week.

# m  h  dom mon dow  command
30 2  *   *   *    /opt/scripts/backup.sh /var/www /backups 7 >> /var/log/backup.log 2>&1
0  *  *   *   *    /opt/scripts/sysinfo.sh 85 || echo "disk warning" | logger -t sysinfo
*/5 * *   *   *    /opt/scripts/healthcheck.sh 127.0.0.1 3000 /health
  • The first line runs at 02:30 every day. The second runs at the start of every hour. The third runs every five minutes.
  • Use full paths in cron. Cron has a very small environment, so a command that works in your terminal can fail there.
  • Send output to a log file with >> file 2>&1, otherwise errors vanish.
  • Check the schedule with a site such as crontab.guru, and make jobs safe to run twice.

Logs

  • journalctl -u servicename shows a service’s logs. Add -f to follow, --since "1 hour ago" to limit the time, and -p err to show only errors.
  • /var/log/syslog (Debian and Ubuntu) or /var/log/messages (Red Hat family) hold general messages.
  • /var/log/auth.log or /var/log/secure show who logged in and who failed.
  • /var/log/nginx/error.log and access.log for a web server.
  • tail -f follows a file, and grep ERROR file filters it.

Logs grow, and a full disk stops servers. The logrotate tool is set up on most systems to compress and delete old logs. Check that your own application’s log file is covered.

Architecture diagram

Here is the idea as a simple picture. You can use the same diagram in your own notes.

flowchart LR
  Boot[Machine boots] --> SD[systemd]
  SD --> Svc[Your service]
  Svc -->|crash| SD
  SD -->|restart| Svc
  Svc --> J[(journal logs)]
  Cron[cron] --> Job[Scheduled script]
  Me[You via SSH key] --> Server[(Server)]

How to check it worked

  • systemctl status shows your service as active (running).
  • You can log in with your key and not your password.
  • Your cron job leaves lines in its log file.

How companies use it

Every production Linux application runs under a service manager. Teams log in with SSH keys, often through a bastion host, run backups and checks with cron or timers, and ship logs to a central system. Containers replace some of this, but the same ideas apply inside them.

Common errors and how to fix them

  • Failed to start: code=exited, status=203/EXEC. The ExecStart path is wrong or the file is not executable. Use full paths.
  • Service starts and stops immediately. Read journalctl -u name -e for the error, often a missing environment file or port in use.
  • SSH: Permission denied (publickey). The public key is not in ~/.ssh/authorized_keys on the server, or file modes are wrong.
  • Cron job does nothing. Use full paths, check the time fields and send output to a log.
  • Locked out after changing sshd_config. Keep a second session open while testing and use the provider console as a way back in.

Best practices

  • Run services as a normal user.
  • Use key-based SSH and turn off password login after testing.
  • Keep secrets in a protected EnvironmentFile.
  • Log to the journal or to a rotated file.
  • Make cron jobs safe to run twice.

Interview questions with simple answers

  1. What is systemd? The init system that starts and supervises services on most modern Linux distributions.
  2. start vs enable? start runs now. enable starts at boot.
  3. How do you see a service log? journalctl -u name, add -f to follow.
  4. How does SSH key login work? The server checks that you hold the private key matching the public key it has stored.
  5. How do you set up key login? ssh-keygen then ssh-copy-id user@host.
  6. What are the five cron fields? Minute, hour, day of month, month, day of week.
  7. Why use full paths in cron? Cron has a small environment, so commands may not be found.
  8. What is a unit file? A file that tells systemd how to run a service.
  9. How do you disable root SSH login? Set PermitRootLogin no in sshd_config and reload ssh.
  10. What does logrotate do? Compresses and removes old logs so disks do not fill up.

Practical exercises

Try each one yourself before you look at the hint. Struggling for a few minutes is how the skill sticks.

  1. Install nginx and practise start, stop, enable and status. Hint: systemctl commands.
  2. Write a unit for a tiny script that prints a line every few seconds. Hint: Use a while loop and sleep.
  3. Create an SSH key and add it to a practice server. Hint: ssh-keygen, ssh-copy-id.
  4. Add a cron job that logs the date every minute, then remove it. Hint: crontab -e.
  5. Find the last five failed login attempts. Hint: /var/log/auth.log or journalctl -u ssh.

Mini project: Run your app as a service

Take a small Node or Python web app. Write a unit file, load it, enable it, kill the process to prove it restarts, and read its logs with journalctl. Document each command in a README.

Knowledge test

Answer the ten questions in the quiz at the end of this lesson. You pass with 60 percent. If an answer is wrong, read the explanation, then reread the part of the lesson it points to.

Frequently asked questions

What is the difference between start and enable?

Start runs the service now. Enable makes it start automatically at every boot. You usually want both, and enable --now does both in one command.

Why is my cron job not running?

Common causes are a wrong time field, a relative path, a missing environment, or no permission to run the script. Use full paths, send the output to a log file and check the cron log.

Is it safe to share my SSH public key?

Yes. The public key is meant to be shared. Never share the private key (the file without .pub).

Practise with interview questions