Ravindra BagaleCourses & study guides मराठी

Chapter 4: Linux Ops Refresh for DevOps

DevOps

4.3 Logs — journalctl and tail -f

Why: the problem

Think of Zomato at lunch time. The order API is returning errors for some users, but not for all. The three checks from lesson 4.1 are green: the process runs, the port is open, the disk is fine. So where is the problem? The answer is almost always in the logs. A log is a diary that a program writes while it runs. Every request, warning and error goes there with a time. On Linux there are two main places to read logs. Services managed by systemd write to the journal, and you read it with journalctl. Many apps like nginx also write plain text files under /var/log, and you read them with tail -f. The real skill is to watch the log live while you repeat the problem with curl. Then you see the exact error line appear the moment it happens. In this lesson you will do exactly that on a small app.

What we will build

You will run a small Python web service as a systemd unit on an Ubuntu 24.04 machine (an EC2 instance or a local VM with systemd). You will read its logs with journalctl, filter by time and priority, and follow them live. Then you will put nginx in front of it and read the nginx access and error logs with tail -f and grep. Finally you will cause a real 502 error and find the cause by reading both logs side by side.

What: every term in plain English

  • Log — Text lines a program writes about what it is doing, with a time on each line.
  • journal — The log store of systemd. Every service started by systemd writes here.
  • journalctl — The command to read the journal.
  • -u — Unit. journalctl -u nginx shows only nginx logs.
  • -f — Follow. Keeps printing new lines as they arrive. Stop with Ctrl+C.
  • /var/log — The classic folder for log files on Linux.
  • access.log — nginx file with one line per request: who, when, which URL, which status code.
  • error.log — nginx file with problems like upstream not reachable.
  • Status code — A number in the reply. 200 OK, 404 not found, 500 app error, 502 bad gateway.
Use a VM with systemd Install nginx and Python Create the app Create the unit Read its logs Follow nginx access log Repeat the problem
Reproduce with curl while the log is followed, top to bottom

How: step by step

  1. Use a VM with systemd

    ssh -i ~/.ssh/lab.pem ubuntu@13.233.10.20
    

    What it does: journalctl needs systemd, so use an EC2 instance or VM, not a plain container.

    Output

    Welcome to Ubuntu 24.04 LTS
    
  2. Install nginx and Python

    sudo apt-get update -qq && sudo apt-get install -y -qq nginx python3
    

    What it does: The web server and the language for our small app.

    Output

    Setting up nginx ...
    
  3. Create the app

    sudo mkdir -p /opt/orders && sudo cp ~/app.py /opt/orders/app.py
    

    What it does: Copies the app from Example 1 into place.

    Output

    (no output)
    
  4. Create the unit

    sudo cp ~/orders.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable --now orders
    

    What it does: Starts the app as a service, now and on boot.

    Output

    Created symlink /etc/systemd/system/multi-user.target.wants/orders.service
    
  5. Read its logs

    journalctl -u orders -n 5 --no-pager
    

    What it does: Last five lines of the orders service.

    Output

    Oct 25 10:31:02 ip-10-0-1-20 python3[2210]: orders listening on 127.0.0.1:5000
    
  6. Follow nginx access log

    sudo tail -f /var/log/nginx/access.log
    

    What it does: Watch every request live. Keep this window open.

    Output

    203.0.113.7 - - [25/Oct/2026:10:32:10 +0530] "GET / HTTP/1.1" 200 615
    
  7. Repeat the problem

    curl -s localhost/orders
    

    What it does: In a second window, call the URL while the log window watches.

    Output

    {"orders": 3}
    

Example 1: Run an app under systemd and read its journal

Stack. Ubuntu 24.04, systemd, Python 3.12

Goal. Run an app under systemd and read its journal.

/opt/orders/app.py

from http.server import BaseHTTPRequestHandler, HTTPServer
import json, sys

class H(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/orders":
            body = json.dumps({"orders": 3}).encode()
            self.send_response(200)
        else:
            body = b'{"error": "not found"}'
            self.send_response(404)
            print(f"WARN unknown path {self.path}", file=sys.stderr, flush=True)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(body)

print("orders listening on 127.0.0.1:5000", flush=True)
HTTPServer(("127.0.0.1", 5000), H).serve_forever()

/etc/systemd/system/orders.service

[Unit]
Description=Orders API
After=network.target

[Service]
User=www-data
ExecStart=/usr/bin/python3 /opt/orders/app.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

Read the journal

curl -s localhost:5000/orders
curl -s localhost:5000/menu
journalctl -u orders -n 10 --no-pager
journalctl -u orders --since "10 min ago" -p warning --no-pager

What each line does

  • print(..., flush=True) — Writes to the log at once. Without flush, Python may hold lines in memory.
  • file=sys.stderr — Warnings go to the error stream. systemd stores both streams in the journal.
  • User=www-data — The app runs as a normal user, not root.
  • Restart=on-failure — systemd starts the app again if it crashes.
  • journalctl -u orders -n 10 — Last 10 lines of this unit only.
  • --since "10 min ago" — Only lines from the last 10 minutes. Also works with "2026-10-25 10:00".
  • -p warning — Only warning and worse. Cuts the noise.

Green output

{"orders": 3}
{"error": "not found"}
Oct 25 10:31:02 ip-10-0-1-20 systemd[1]: Started orders.service - Orders API.
Oct 25 10:31:02 ip-10-0-1-20 python3[2210]: orders listening on 127.0.0.1:5000
Oct 25 10:33:40 ip-10-0-1-20 python3[2210]: 127.0.0.1 - - "GET /orders HTTP/1.1" 200 -
Oct 25 10:33:41 ip-10-0-1-20 python3[2210]: WARN unknown path /menu
Oct 25 10:33:41 ip-10-0-1-20 python3[2210]: 127.0.0.1 - - "GET /menu HTTP/1.1" 404 -

Expected result. Every request and warning is in the journal, with time, host and PID. You did not need to know where the app writes files.

Example 2: Put nginx in front and read access and error logs

Stack. nginx 1.24, awk

Goal. Put nginx in front and read access and error logs.

/etc/nginx/sites-available/orders

server {
    listen 80 default_server;
    location / {
        proxy_pass http://127.0.0.1:5000;
    }
}

Enable and test

sudo ln -sf /etc/nginx/sites-available/orders /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
for i in 1 2 3; do curl -s -o /dev/null -w "%{http_code}\n" localhost/orders; done
sudo tail -n 3 /var/log/nginx/access.log
sudo awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c

What each line does

  • proxy_pass — nginx sends each request to the app on port 5000.
  • ln -sf — Makes our site the active one.
  • -w "%{http_code}" — curl prints only the status code. Easy to count.
  • tail -n 3 — Last three lines of the access log.
  • awk {print $9} — The 9th field of each access line is the status code.
  • sort | uniq -c — Counts how many times each status code appears.

Green output

200
200
200
127.0.0.1 - - [25/Oct/2026:10:36:01 +0530] "GET /orders HTTP/1.1" 200 13 "-" "curl/8.5.0"
127.0.0.1 - - [25/Oct/2026:10:36:01 +0530] "GET /orders HTTP/1.1" 200 13 "-" "curl/8.5.0"
127.0.0.1 - - [25/Oct/2026:10:36:01 +0530] "GET /orders HTTP/1.1" 200 13 "-" "curl/8.5.0"
      4 200
      1 404

Expected result. You can count good and bad requests in one line. This is the first thing to do when users say "some requests fail".

Example 3: Cause a 502 and find it in two logs

Stack. nginx, systemd, journalctl

Goal. Cause a 502 and find it in two logs.

Break the app

sudo systemctl stop orders
curl -s -o /dev/null -w "%{http_code}\n" localhost/orders

Read both logs

sudo tail -n 2 /var/log/nginx/error.log
journalctl -u orders -n 3 --no-pager
systemctl is-active orders

Fix and watch it recover

sudo systemctl start orders
curl -s -o /dev/null -w "%{http_code}\n" localhost/orders
sudo grep -c " 502 " /var/log/nginx/access.log

What each line does

  • systemctl stop orders — We stop the app on purpose. nginx is still up.
  • 502 — Bad gateway: nginx is fine, but the app behind it did not answer.
  • error.log — Tells you why: connection refused to 127.0.0.1:5000.
  • journalctl -u orders — Confirms the app was stopped, and when.
  • grep -c " 502 " — Counts how many users got a 502 during the outage.

Green output

502
2026/10/25 10:38:12 [error] 1890#1890: *12 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /orders HTTP/1.1", upstream: "http://127.0.0.1:5000/orders"
Oct 25 10:38:05 ip-10-0-1-20 systemd[1]: Stopping orders.service - Orders API...
Oct 25 10:38:05 ip-10-0-1-20 systemd[1]: orders.service: Deactivated successfully.
inactive
200
1

Expected result. nginx error.log pointed to port 5000, and the journal told you the app stopped and when. You fixed the right thing in one try.

Example 4: Search old logs, rotated and zipped

Stack. logrotate, zgrep, journalctl

Goal. Search old logs, rotated and zipped.

Find errors across days

ls -lh /var/log/nginx/
sudo zgrep -h " 502 " /var/log/nginx/access.log* | wc -l
sudo journalctl -u nginx --since yesterday --until "1 hour ago" --no-pager | tail -3
journalctl --disk-usage

What each line does

  • access.log.1, access.log.2.gz — logrotate moves old logs aside and zips them, so the disk does not fill.
  • zgrep — grep that also reads .gz files. -h hides file names.
  • wc -l — Counts the matching lines.
  • --since yesterday --until — A time window. Great for "it broke last night".
  • --disk-usage — How much disk the journal uses.

Green output

-rw-r----- 1 www-data adm  2.1K Oct 25 10:38 access.log
-rw-r----- 1 www-data adm   14K Oct 24 23:59 access.log.1
-rw-r----- 1 www-data adm  3.2K Oct 23 23:59 access.log.2.gz
-rw-r----- 1 www-data adm   410 Oct 25 10:38 error.log
7
Oct 25 09:12:44 ip-10-0-1-20 systemd[1]: Reloading nginx.service
Oct 25 09:12:44 ip-10-0-1-20 systemd[1]: Reloaded nginx.service
Archived and active journals take up 48.0M in the file system.

Expected result. You can search days of logs, including zipped ones, in seconds.

Verify: did it work?

  1. Logs show the recovery

    journalctl -u orders -n 2 --no-pager
    

    What it does: After the fix you must see the start line.

    Output

    Oct 25 10:39:00 ip-10-0-1-20 systemd[1]: Started orders.service - Orders API.
    Oct 25 10:39:00 ip-10-0-1-20 python3[2301]: orders listening on 127.0.0.1:5000
    
  2. No new 502 lines

    sudo tail -n 20 /var/log/nginx/access.log | grep -c " 502 " || true
    

    What it does: Zero new 502s means users are fine now.

    Output

    0
    

When it is red 1

-- No entries --

Cause. journalctl found nothing for that unit or time. Wrong unit name, or the app writes only to a file.

Fix, step by step

  1. Run systemctl list-units --type=service | grep -i orders to get the real name.
  2. Widen the time with --since "1 hour ago".
  3. Check the app config for a log file path and tail that instead.

When it is red 2

tail: cannot open '/var/log/nginx/access.log' for reading: Permission denied

Cause. nginx logs belong to www-data and group adm.

Fix, step by step

  1. Use sudo tail.
  2. Or add your user to the adm group: sudo usermod -aG adm ubuntu, then log in again.

When it is red 3

Hint: You are currently not seeing messages from other users and the system.

Cause. Your user is not in the systemd-journal or adm group, so journalctl shows only your own lines.

Fix, step by step

  1. Use sudo journalctl.
  2. Or add your user to systemd-journal group.

Cleanup

  1. Stop the lab services

    sudo systemctl disable --now orders && sudo rm /etc/systemd/system/orders.service && sudo systemctl daemon-reload
    

    What it does: Removes the demo app cleanly.

    Output

    Removed "/etc/systemd/system/multi-user.target.wants/orders.service".
    
  2. Terminate the EC2 lab

    aws ec2 terminate-instances --instance-ids i-0abc123def4567890
    

    What it does: Stops paying for the lab machine.

    Output

    "CurrentState": {"Code": 32, "Name": "shutting-down"}
    

Ravindra Bagale's Tip

Do not guess. Follow the log in one window and curl in another. The error will show itself. Keep that in mind!

Practice tasks

Easy Count status codes

Why: The first question in any incident is how many users are hit.

What to do: Count 200, 404 and 502 in your access.log.

How:
  1. Use awk, sort and uniq -c.

Check: You get a small table of codes and counts.

Medium Find the slowest hour

Why: Traffic peaks explain many errors.

What to do: Count requests per hour from access.log.

How:
  1. awk -F: {print $2} access.log | sort | uniq -c

Check: You can say which hour was busiest.

Hard Live error watcher

Why: On-call people want only errors on screen.

What to do: Follow the access log and show only 5xx lines.

How:
  1. tail -f access.log | grep --line-buffered " 5[0-9][0-9] "

Check: Only error lines appear as you curl.

Easy Say reading Linux logs in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about reading Linux logs for a fresher who knows only basic Linux commands.

How:
  1. Write the problem it solves.
  2. Write the one command you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Make a safe practice server

Why: Ops commands can stop services or fill disks. Practice on a machine you can throw away.

What to do: Start a throwaway Ubuntu machine and do this lesson there.

How:
  1. docker run -it --rm --name ops-lab ubuntu:24.04 bash
  2. Or launch a t3.micro Ubuntu 24.04 EC2 with port 22 open only to your IP.
  3. Delete it when you are done.

Check: All practice happens on the lab machine, not on a real server.

Medium Repeat it on Amazon Linux

Why: Companies use both Ubuntu and Amazon Linux. Package names and log files differ a little.

What to do: Do the main steps of this lesson again on Amazon Linux 2023.

How:
  1. docker run -it --rm amazonlinux:2023 bash
  2. Install tools with dnf instead of apt.
  3. Note every difference in your notes.

Check: You can list two differences between Ubuntu and Amazon Linux for this lesson.

Medium Break it on purpose

Why: You must know the red message by face. In a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers the right command. A short page saves the on-call person.

What to do: Write a runbook page for this lesson.

How:
  1. Title, when to use, exact command, how to check, how to undo.

Check: A teammate can follow it alone.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the command you ran, and one error you hit.

Check: Your answer has a real command and a real error message.

Hard Draw the flow top to bottom

Why: A drawing shows the order of checks and what happens on failure.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the user complaint, show each check as a box, end at the fix.

Check: Each box matches a real command you ran.

Homework: try at home

Try at home

At home, run the orders app and nginx. Open two terminals. In one, run sudo tail -f on both nginx logs with tail -f access.log error.log. In the other, stop and start the app and call it with curl. Write down every line that appears and what it means.

Recap

  • Logs are the diary of a program, with times.
  • systemd services: journalctl -u name, with -n, -f, --since and -p.
  • File logs: tail -f and grep under /var/log.
  • Follow the log while you repeat the problem with curl.
  • A 502 means look at the app behind nginx, in both logs.

FAQ

Where does a Docker container write logs?

To its stdout. Read them with docker logs -f name. Same idea as journalctl.

Why are logs in /var/log sometimes empty?

The app may log only to the journal, or logrotate just moved the file to .1.

How long does the journal keep logs?

Until it reaches its size limit, set in /etc/systemd/journald.conf.

Should apps log passwords?

Never. Logs are read by many people and shipped to tools like CloudWatch.

What is the difference between access and error log?

Access has one line per request. Error has only problems nginx itself saw.

Interview questions

  1. How do you troubleshoot intermittent 5xx errors?

    Count status codes in the access log, find the time window, then read the error log and app journal for that window with --since and --until.

  2. How do you read logs of a systemd service?

    journalctl -u service -n 100 --no-pager, add -f to follow, --since for time, and -p err for only errors.

  3. What causes a 502 vs a 504 in nginx?

    502 means the upstream refused or closed the connection. 504 means the upstream was too slow and nginx timed out.

  4. How do you stop logs from filling the disk?

    logrotate for files, journald size limits for the journal, and shipping logs to a central tool.

  5. What is the first thing you check when a user reports an error at a certain time?

    The logs for that time window, using grep on the access log and journalctl with --since and --until.

Quick quiz

Q1. Which command reads logs of one systemd service?

journalctl -u name

Q2. What does tail -f do?

Keeps printing new lines as they are written.

Q3. What does a 502 from nginx mean?

nginx is fine but the app behind it did not answer.

Q4. How do you search zipped old logs?

zgrep

Q5. Which option shows only warnings and worse?

-p warning

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards