Lab 8.1 - Gerenciamento de Serviços systemd
Objetivos
Ao final deste lab, você será capaz de:
- Utilizar o systemctl para gerenciar serviços
- Compreender os estados dos serviços
- Iniciar, parar, reiniciar serviços
- Ativar/desativar serviços na inicialização
- Visualizar os logs dos serviços
Pré-requisitos
- Ubuntu 24.04 instalado
- Acesso sudo
- Terminal aberto
Exercício 1: Comandos Básicos
Etapa 1: Ver o Estado de um Serviço
# Estado de um serviço
systemctl status sshd
# ou
systemctl status ssh
# Estado resumido
systemctl is-active sshd
systemctl is-enabled sshd
systemctl is-failed sshd
Etapa 2: Listar Serviços
# Todos os serviços
systemctl list-units --type=service
# Serviços ativos
systemctl list-units --type=service --state=running
# Serviços inativos
systemctl list-units --type=service --state=inactive
# Serviços com falha
systemctl list-units --type=service --state=failed
Exercício 2: Controle de Serviços
Etapa 1: Iniciar/Parar
# Iniciar um serviço
sudo systemctl start sshd
# Parar um serviço
sudo systemctl stop sshd
# Reiniciar
sudo systemctl restart sshd
# Recarregar configuração (se suportado)
sudo systemctl reload sshd
Etapa 2: Ativar na Inicialização
# Ativar (inicialização automática)
sudo systemctl enable sshd
# Desativar
sudo systemctl disable sshd
# Ativar e iniciar
sudo systemctl enable --now sshd
Etapa 3: Mascarar um Serviço
# Mascarar (impede inicialização manual também)
sudo systemctl mask sshd
# Desmascarar
sudo systemctl unmask sshd
Exercício 3: Logs dos Serviços
Etapa 1: journalctl
# Logs de um serviço
sudo journalctl -u sshd
# Últimas linhas
sudo journalctl -u sshd -n 50
# Acompanhar em tempo real
sudo journalctl -u sshd -f
# Logs desde hoje
sudo journalctl -u sshd --since today
# Logs de um período
sudo journalctl -u sshd --since "2024-12-01" --until "2024-12-31"
Etapa 2: Níveis de Log
# Por prioridade
sudo journalctl -u sshd -p err
sudo journalctl -u sshd -p warning
# Combinações
sudo journalctl -u sshd -p err --since "1 hour ago"
Exercício 4: Serviços do Sistema
Etapa 1: Serviços Essenciais
# Ver os serviços do sistema
systemctl list-units --type=service | grep systemd
# Estado do systemd
systemctl status
# Serviços críticos
systemctl list-units --type=service --state=failed
Etapa 2: Analisar Dependências
# Dependências de um serviço
systemctl list-dependencies sshd
# Serviços que dependem de sshd
systemctl list-dependencies --reverse sshd
Exercício 5: Prática com nginx
Etapa 1: Instalação e Configuração
# Instalar nginx
sudo apt update
sudo apt install -y nginx
# Verificar o estado
systemctl status nginx
# Iniciar
sudo systemctl start nginx
# Ativar na inicialização
sudo systemctl enable nginx
Etapa 2: Gerenciamento
# Reiniciar
sudo systemctl restart nginx
# Recarregar configuração
sudo systemctl reload nginx
# Ver os logs
sudo journalctl -u nginx -f
Etapa 3: Teste
# Testar o serviço
curl http://localhost
# Ver os processos
ps aux | grep nginx
Exercício 6: Script de Gerenciamento
Etapa 1: Script Básico
# Script para gerenciar um serviço
cat > manage-service.sh << 'EOF'
#!/bin/bash
SERVICE=$1
ACTION=$2
if [ -z "$SERVICE" ] || [ -z "$ACTION" ]; then
echo "Usage: $0 service {start|stop|restart|status|enable|disable}"
exit 1
fi
case $ACTION in
start)
sudo systemctl start "$SERVICE"
;;
stop)
sudo systemctl stop "$SERVICE"
;;
restart)
sudo systemctl restart "$SERVICE"
;;
status)
systemctl status "$SERVICE"
;;
enable)
sudo systemctl enable "$SERVICE"
;;
disable)
sudo systemctl disable "$SERVICE"
;;
*)
echo "Ação desconhecida: $ACTION"
exit 1
;;
esac
EOF
chmod +x manage-service.sh
# Utilizar
./manage-service.sh nginx status
./manage-service.sh nginx restart
Verificação
Checklist
Verifique se você consegue:
- Ver o estado dos serviços (systemctl status)
- Listar os serviços (list-units)
- Iniciar/parar serviços
- Ativar/desativar na inicialização
- Ver os logs (journalctl)
- Analisar dependências
- Gerenciar serviços comuns (nginx, sshd)
Perguntas para Reflexão
-
Qual a diferença entre start e enable?
- start: Inicia agora
- enable: Ativa na inicialização do sistema
-
Quando usar reload vs restart?
- reload: Recarrega a configuração sem interrupção
- restart: Reinicia completamente (com interrupção)
-
Por que usar journalctl ao invés de /var/log?
- journalctl: Logs centralizados do systemd, mais moderno
- /var/log: Logs tradicionais, ainda disponíveis
Próximos Passos
- Lab 8.2: Serviços Personalizados
- Lab 8.3: Cron Avançado e systemd Timers
- Capítulo 8.1: Gerenciamento de Serviços systemd
Lab criado em: Dezembro 2024 - Testado no Ubuntu 24.04