Skip to Content
DocumentaciónOperacionesAdministración del sistemasystemd y gestión de servicios

systemd y gestión de servicios

26.10 Diferencias de versión

26.10 usa systemd 261.3 y elimina systemd-sysv-generator. Los scripts /etc/init.d personalizados ya no pueden depender de los servicios generados. Migre a unidades systemd nativas y pruebe la activación, parada, reinicio y arranque. Notas de la versión oficial 

systemd es el sistema de inicio y administrador de servicios para Ubuntu 26.04, responsable de iniciar el sistema, administrar servicios y demonios. Dominar systemd es una habilidad esencial para la administración del sistema Ubuntu.

Conceptos básicos de systemctl

Gestión del estado del servicio

# 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 nginx

Gestión del servicio de arranque

# 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 nginx

Ver información de servicio

# 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 nginx

Archivos de unidad de servicio

Ubicaciones de archivos de unidad

Los archivos de la unidad de servicio systemd se almacenan en las siguientes ubicaciones, en orden de prioridad (de mayor a menor):

CaminoDescripción
/etc/systemd/system/Configuraciones de administrador personalizadas, máxima prioridad
/run/systemd/system/Archivos unitarios generados en tiempo de ejecución
/lib/systemd/system/Archivos de unidad predeterminados instalados por paquetes

Ver archivos de unidades

# 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.service

Estructura del archivo unitario

Un archivo de unidad de servicio típico tiene tres secciones:

[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.target

Tipos de servicios comunes

TipoDescripción
simplePor defecto; el proceso iniciado por ExecStart es el proceso principal
forkingEl servicio bifurca un proceso hijo; El inicio se considera completo cuando el padre sale.
oneshotTarea única; Se considera completo cuando el proceso finaliza.
notifyEl servicio notifica a systemd a través de sd_notify cuando se completa el inicio
idleSimilar a simple, pero espera a que finalicen otras tareas antes de comenzar

Reiniciar políticas

OpciónDescripción
noNo reiniciar automáticamente (predeterminado)
on-successReiniciar en salida normal
on-failureReiniciar en salida anormal
on-abnormalReiniciar cuando lo mata la señal o el tiempo de espera
on-abortReiniciar cuando lo mata una señal no detectada
alwaysReinicie siempre independientemente del motivo de salida

Crear servicios personalizados

Ejemplo: Servicio de aplicación Node.js

Crea un archivo de unidad:

sudo nano /etc/systemd/system/myapp.service

Añade el siguiente contenido:

[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.target

Habilite e inicie el servicio:

# 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 -f

Ejemplo: Servicio de aplicación 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.target

Ejemplo: Servicio con 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.target

Uso de anulaciones para modificar servicios existentes

No se recomienda modificar archivos directamente en /lib/systemd/system/. En su lugar, utilice anulaciones:

# Create an override file sudo systemctl edit nginx.service

Esto abre un editor donde puede agregar anulaciones de configuración:

[Service] # Add memory limit MemoryMax=512M # Change restart policy Restart=always RestartSec=3

El archivo de anulación se guarda en /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 nginx

Comandos de gestión del 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 hibernate

Límites de recursos

Puede establecer límites de recursos en archivos de unidades de servicio:

[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=65535

Solución 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.service

Artículos relacionados