Skip to content

Latest commit

 

History

History
133 lines (107 loc) · 4.79 KB

systemd-journal.md

File metadata and controls

133 lines (107 loc) · 4.79 KB

Cheatsheet — systemd / journalctl (Labs 12, 16)

Ciclo de vida del servicio

sudo systemctl start myapp           # arrancar
sudo systemctl stop myapp            # parar (SIGTERM)
sudo systemctl restart myapp         # stop + start (downtime)
sudo systemctl reload myapp          # recargar config sin parar (si lo soporta)
sudo systemctl status myapp --no-pager  # estado + últimas líneas de log
sudo systemctl enable myapp          # arrancar al boot
sudo systemctl enable --now myapp    # enable + start inmediato
sudo systemctl disable myapp         # no arrancar al boot
sudo systemctl is-enabled myapp      # ¿arranca al boot?
sudo systemctl daemon-reload         # OBLIGATORIO después de editar unit file

Equivalencia systemd ↔ Docker (Lab 06-B)

systemd Docker Compose
systemctl start docker compose start
systemctl stop docker compose stop
systemctl restart docker compose restart
systemctl status docker compose ps
systemctl enable restart: unless-stopped (en compose)
journalctl -u svc docker compose logs svc
journalctl -f docker compose logs -f
daemon-reload docker compose up -d (relee config)

journalctl — logs del servicio

journalctl -u myapp -f                    # follow (tiempo real)
journalctl -u myapp -n 100 --no-pager     # últimas 100 líneas
journalctl -u myapp --since "10 min ago"  # ventana temporal
journalctl -u myapp --since "2026-08-03 16:00"  # desde hora
journalctl -u myapp -p err..alert         # solo errores+
journalctl -u myapp -o short-iso          # timestamps ISO

Unit file — estructura (Lab 06-A)

[Unit]
Description=Mi App Java
After=network-online.target mysql.service
# After = arrancar DESPUÉS de estos servicios

[Service]
User=appsvc                          # NO root (seguridad)
EnvironmentFile=-/etc/myapp/app.env   # secrets (-=no falla si falta)
ExecStart=/usr/bin/java -Xms256m -Xmx512m -jar /opt/myapp/current/app.jar
Restart=on-failure                    # auto-restart si crashea
RestartSec=5                          # esperar 5s (anti-crashloop)
SuccessExitStatus=143                 # Java SIGTERM = 128+15 = 143

# Hardening
NoNewPrivileges=true                  # no escalar privilegios
PrivateTmp=true                       # /tmp aislado

[Install]
WantedBy=multi-user.target            # arrancar con systemctl enable

Restart policies (Lab 06-E)

Directiva Comportamiento
Restart=no no reiniciar (default, MALO para servicios)
Restart=on-failure reiniciar si exit code ≠ 0 (recomendado)
Restart=always reiniciar SIEMPRE excepto systemctl stop
RestartSec=5 esperar 5s entre crash y restart

Docker equivalentes:

  • restart: "no" = Restart=no
  • restart: on-failure = Restart=on-failure
  • restart: unless-stopped = Restart=always (excepto docker stop)

kill vs stop (para probar auto-restart)

  • docker compose kill / kill -9 → SIGKILL = crash → dispara restart
  • docker compose stop / kill → SIGTERM = stop limpio → NO dispara on-failure

4 fallos comunes de deploy (Lab 06-D)

Fallo Síntoma Diagnóstico
Path incorrecto status=203/EXEC which java; ls -l app.jar
Permission denied servicio no arranca ls -la; namei -l path
Puerto ocupado "Address already in use" lsof -nP -iTCP:8080
DB connection failed CommunicationsLinkFailure systemctl status mysql

Hardening avanzado (Lab 16-A)

# Controles adicionales para producción
ProtectSystem=strict           # filesystem read-only excepto WritablePaths
ProtectHome=true               # /home inaccesible
ReadWritePaths=/var/log/myapp  # solo puede escribir acá
CapabilityBoundingSet=         # sin capabilities extra (vacío)
SystemCallFilter=@system-service  # solo syscalls necesarias
MemoryLimit=512M               # límite duro de memoria (cgroup)
LimitNOFILE=65535              # máximo de file descriptors

Prioridad de controles (Lab 16-A)

  1. User= (no root) — sin esto, todo lo demás es inútil
  2. Restart=on-failure — disponibilidad básica
  3. NoNewPrivileges — bloquear escalamiento
  4. PrivateTmp — aislamiento básico
  5. ProtectSystem=strict — filesystem read-only (más avanzado)

EnvironmentFile seguro (Lab 06-D)

chmod 640 /etc/myapp/app.env       # owner+group leen, otros no
chown root:appsvc /etc/myapp/app.env  # root owner, appsvc group

Checklist pre-producción (Lab 16-D)

[  ] App no corre como root (User=appsvc)
[  ] Restart=on-failure + RestartSec
[  ] EnvironmentFile con chmod 640
[  ] Actuator limitado (solo /health)
[  ] Grants MySQL mínimos
[  ] Backups automatizados
[  ] Alertas de health
[  ] Runbook documentado