systemd e gerenciamento de serviços
Diferenças de versão 26.10
26.10 usa systemd 261.3 e remove systemd-sysv-generator. Os scripts /etc/init.d customizados não podem mais contar com serviços gerados. Migre para unidades systemd nativas e teste o início, a parada, a reinicialização e a ativação da inicialização. Notas de lançamento oficiais
systemd é o sistema init e gerenciador de serviços para Ubuntu 26.04, responsável por inicializar o sistema, gerenciar serviços e daemons. Dominar systemd é uma habilidade essencial para a administração do sistema Ubuntu.
Noções básicas de systemctl
Gerenciando o estado do serviço
# Start a service
sudo systemctl start nginx
# Stop a service
sudo systemctl stop nginx
# Restart a service
sudo systemctl restart nginx
# Reload configuration (without interrupting the service)
sudo systemctl reload nginx
# Reload if supported, otherwise restart
sudo systemctl reload-or-restart nginx
# Check service status
systemctl status nginxGerenciamento de serviço de inicialização
# Enable a service at boot
sudo systemctl enable nginx
# Disable a service at boot
sudo systemctl disable nginx
# Enable and start immediately
sudo systemctl enable --now nginx
# Prevent a service from being started (including manually)
sudo systemctl mask nginx
# Remove the mask
sudo systemctl unmask nginxVisualizando informações de serviço
# List all running services
systemctl list-units --type=service --state=running
# List all installed services
systemctl list-unit-files --type=service
# List failed services
systemctl list-units --failed
# View a service's dependencies
systemctl list-dependencies nginx
# View detailed service properties
systemctl show nginx
# Check if a service is active
systemctl is-active nginx
# Check if a service is enabled at boot
systemctl is-enabled nginxArquivos de Unidade de Serviço
Locais de arquivos de unidade
Os arquivos da unidade de serviço systemd são armazenados nos seguintes locais, em ordem de prioridade (da maior para a menor):
| Caminho | Descrição |
|---|---|
/etc/systemd/system/ | Configurações de administrador personalizadas, prioridade mais alta |
/run/systemd/system/ | Arquivos de unidade gerados em tempo de execução |
/lib/systemd/system/ | Arquivos de unidade padrão instalados por pacotes |
Visualizando Arquivos de Unidade
# View a service's unit file contents
systemctl cat nginx.service
# View the unit file path
systemctl show -p FragmentPath nginx.service
# Edit a unit file (creates an override)
sudo systemctl edit nginx.service
# Edit the full unit file
sudo systemctl edit --full nginx.serviceEstrutura de arquivo de unidade
Um arquivo de unidade de serviço típico possui três seções:
[Unit]
Description=Service description
Documentation=https://example.com/docs
After=network.target
Wants=network-online.target
Requires=postgresql.service
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/myapp
ExecStartPre=/opt/myapp/pre-start.sh
ExecStart=/opt/myapp/start.sh
ExecStop=/opt/myapp/stop.sh
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
Environment=NODE_ENV=production
EnvironmentFile=/opt/myapp/.env
[Install]
WantedBy=multi-user.targetTipos de serviços comuns
| Tipo | Descrição |
|---|---|
simple | Padrão; o processo iniciado pelo ExecStart é o processo principal |
forking | O serviço bifurca um processo filho; a inicialização é considerada concluída quando o pai sai |
oneshot | Tarefa única; considerado concluído quando o processo termina |
notify | O serviço notifica systemd via sd_notify quando a inicialização for concluída |
idle | Semelhante ao simples, mas espera que outras tarefas terminem antes de começar |
Políticas de reinicialização
| Opção | Descrição |
|---|---|
no | Não reinicie automaticamente (padrão) |
on-success | Reinicie na saída normal |
on-failure | Reiniciar em saída anormal |
on-abnormal | Reiniciar quando morto por sinal ou tempo limite |
on-abort | Reinicie quando morto por um sinal não detectado |
always | Sempre reinicie independentemente do motivo da saída |
Criando serviços personalizados
Exemplo: Serviço de Aplicativo Node.js
Crie um arquivo de unidade:
sudo nano /etc/systemd/system/myapp.serviceAdicione o seguinte conteúdo:
[Unit]
Description=My Node.js Application
After=network.target
[Service]
Type=simple
User=nodeapp
Group=nodeapp
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
Environment=NODE_ENV=production PORT=3000
# Security hardening
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/myapp/data
PrivateTmp=yes
[Install]
WantedBy=multi-user.targetHabilite e inicie o serviço:
# Reload systemd configuration
sudo systemctl daemon-reload
# Start the service
sudo systemctl enable --now myapp.service
# Check status
systemctl status myapp.service
# View logs
journalctl -u myapp.service -fExemplo: Serviço de Aplicativo Python
[Unit]
Description=Python Flask Application
After=network.target
[Service]
Type=simple
User=flask
Group=flask
WorkingDirectory=/opt/flask-app
ExecStart=/opt/flask-app/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app
Restart=always
RestartSec=5
Environment=FLASK_ENV=production
[Install]
WantedBy=multi-user.targetExemplo: Atendimento com Watchdog
[Unit]
Description=Critical Service with Watchdog
After=network.target
[Service]
Type=notify
ExecStart=/opt/critical/run.sh
WatchdogSec=30
Restart=on-failure
RestartSec=5
# Auto-restart on failure, up to 5 attempts
StartLimitIntervalSec=300
StartLimitBurst=5
[Install]
WantedBy=multi-user.targetUsando substituições para modificar serviços existentes
Não é recomendado modificar diretamente os arquivos em /lib/systemd/system/. Em vez disso, use substituições:
# Create an override file
sudo systemctl edit nginx.serviceIsso abre um editor onde você pode adicionar substituições de configuração:
[Service]
# Add memory limit
MemoryMax=512M
# Change restart policy
Restart=always
RestartSec=3O arquivo de substituição é salvo em /etc/systemd/system/nginx.service.d/override.conf.
# View the merged full configuration
systemctl cat nginx.service
# Reload configuration
sudo systemctl daemon-reload
sudo systemctl restart nginxComandos de gerenciamento do sistema
# View boot time
systemd-analyze
# View boot time per service (sorted)
systemd-analyze blame
# View the boot critical chain
systemd-analyze critical-chain
# View the current default target
systemctl get-default
# Set the default target
sudo systemctl set-default multi-user.target # Command-line mode
sudo systemctl set-default graphical.target # Graphical mode
# Shutdown and reboot
sudo systemctl poweroff
sudo systemctl reboot
# Suspend and hibernate
sudo systemctl suspend
sudo systemctl hibernateLimites de recursos
Você pode definir limites de recursos em arquivos de unidades de serviço:
[Service]
# CPU limit
CPUQuota=50%
# Memory limit
MemoryMax=1G
MemoryHigh=800M
# I/O limit
IOWeight=100
IOReadBandwidthMax=/dev/sda 10M
# Process count limit
TasksMax=100
# File descriptor limit
LimitNOFILE=65535Solução de problemas
# View the reason a service failed
systemctl status myapp.service
journalctl -u myapp.service --no-pager -n 50
# Validate unit file syntax
systemd-analyze verify /etc/systemd/system/myapp.service
# View systemd's own logs
journalctl -b _PID=1
# Reset the failure count
sudo systemctl reset-failed myapp.serviceArtigos relacionados
- Consultas de log do journalctl - Usando o journalctl para visualizar e filtrar logs de serviço systemd
- Tarefas agendadas (cron) - Configurando tarefas agendadas periódicas com cron e temporizadores systemd