Entender y administrar systemd
Aprender los principios básicos del sistema de inicio systemd: como configurarlo y usarlo para administrar el sistema.
Entender systemd
Systemd es un administrador del sistema y los servicios para Linux, compatible con scripts de inicio SysV y LSB. Systemd proporciona:
-
Capacidades agresivas de paralelización
-
Usa socket y activación D-Bus para el inicio de los servicios
-
Ofrece arranque de demonios a demanda, mantiene rastreo de los procesos usando Linux cgroups
-
Admite la creación de instantáneas y restauración del estado del sistema
-
Mantiene puntos de montaje y automontaje
-
Implementa un elaborado servicio de control lógico transaccional basado en la dependencia.
El comando systemctl
en la principal herramienta para administrar systemd. Combina la funcionalidad de los comandos service
y chkconfig
de SysVinit en una herramienta que usted puede usar para habilitar o deshabilitar servicios permanentemente o solo para la sesión actual.
Systemd gestiona las llamadas unidades, que son representaciones de los recursos y servicios del sistema. La siguiente lista muestra los tipos de unidades que systemd puede gestionar:
- service (servicio)
-
Un servicio en el sistema, incluyendo las instrucciones para arrancar, reiniciar y parar el servicio.
- socket
-
Un socket de red asociado con un servicio.
- device (dispositivo)
-
Un dispositivo gestionado específicamente con systemd.
- mount
-
Un punto de montaje gestionado con systemd.
- automount
-
Un punto de montaje montado automáticamente en el arranque.
- swap
-
Espacio swap (de intercambio) en el sistema.
- target
-
Un punto de sincronización para otras unidades. Utilizado usualmente para iniciar servicios habilitados en el arranque.
- path (ruta)
-
Una ruta para activación basada en ruta. Por ejemplo, usted puede iniciar servicios en base al estado de una ruta, como si existe o no.
- timer (temporizador)
-
Un temporizador para planificar la activación de otra unidad.
- snapshot (instantánea)
-
Una instantánea del estado actual de systemd. Usado normalmente para revertir después de realizar cambios temporales en systemd.
- slice
-
Restricción de recursos a través de nodos Grupo de Control Linux (cgroups).
- scope (alcance)
-
Información desde las interfaces bus systemd. Normalmente usado para gestionar procesos externos al sistema.
Iniciar, detener y consultar servicios systemd
Usted puede llevar a cabo diversas tareas de administración para controlar los servicios systemd utilizando el comando systemctl
. Lo siguiente es un conjunto de los comandos ejemplo para demostrar como usar systemctl
para administrar servicios systemd.
Requisitos previos
Usted tiene que acceder con un usuario con permisos a nivel de administrador.
Procedimiento
Los siguientes comando controlan el servicio foo
:
-
Activar un servicio inmediatamente:
# systemctl start foo
-
Desactivar un servicio inmediatamente:
# systemctl stop foo
-
Reiniciar un servicio:
# systemctl restart httpd
-
Mostrar el estado de un servicio, incluyendo si está corriendo o no:
# systemctl status foo
-
Habilitar un servicio para ser iniciado en el arranque:
# systemctl enable foo
-
Deshabilitar un servicio para que no se inicie durante el arranque:
# systemctl disable foo
-
Evitar que un servicio se inicie dinámicamente o incluso manualmente a no ser que esté desenmascarado:
# systemctl mask foo
-
Verificar si un servicio está habilitado o no:
# systemctl is-enabled foo
Información Relacionada
-
Ejecute
man systemctl
para más detalles.
Modificar servicios systemd existentes
Este ejemplo muestra como modificar un servicio existente. La modificación del servicio se almacena dentro de /etc/systemd/system
, es un solo archivo o en un subdirectorio que lleva el nombre del servicio. Por ejemplo, este procedimiento modifica el servicio httpd
.
Requisitos previos
-
Usted tiene que acceder con un usuario con permisos a nivel de administrador.
-
Usted ha configurado un servidor
httpd
corriendo a través de systemd.
Procedimiento
-
Los servicios Systemd pueden ser modificador usando el comando
systemctl edit
.# systemctl edit httpd.service
Esto crea un archivo de anulación
/etc/systemd/system/httpd.service.d/override.conf
y lo abre en su editor de texto. Todo lo que ponga en este archivo será añadido al archivo de servicio existente. -
Añada su configuración personal. Por ejemplo:
[Service] Restart=always RestartSec=30
Para reemplazar una opción que pueda ser ajustada múltiples veces, debe limpiarla primero, de otro modo el archivo de anulación añadirá la opción una segunda vez.
[Service] ExecStart= ExecStart=<new command>
-
Guarde el archivo. Systemd cargará automáticamente la nueva configuración del servicio.
-
Reiniciar el servicio
httpd
:# systemctl restart httpd
Para reemplazar completamente (en lugar de solo añadir/modificar) un archivo de servicio existente, use systemctl edit --full
, por ejemplo systemctl edit --full httpd.service
. Esto creará /etc/systemctl/system/httpd.service
, que será usado en lugar del archivo de servicio existente.
Información Relacionada
-
Vea Parámetros comunes de servicio para más información sobre los parámetros de este procedimiento.
Crear nuevos servicios systemd
Este ejemplo muestra como crear un archivo de unidad para un servicio personalizado. Los archivos personalizados de unidad se ubican en`/etc/systemd/system/` y tienen una extensión .service
. Por ejemplo, un servicio personalizado foo utiliza el archivo de unidad /etc/systemd/system/foo.service
.
Requisitos previos
-
Usted tiene que acceder con un usuario con permisos a nivel de administrador.
Procedimiento
Este procedimiento crea un archivo de configuración básico para controlar el servicio foo
.
-
Cree y edite el nuevo archivo de configuración:
# nano /etc/systemd/system/foo.service
-
Los siguientes pasos describen cada sección y sus parámetros para añadir al archivo:
-
La sección
[Unit]
proporciona información básica sobre el servicio. El serviciofoo
usa los siguientes parámetros:Description
-
Una cadena que describe la unidad. Systemd muestra esta descripción cerca del nombre de la unidad en la interfaz de usuario.
After
-
Define una relación con una segunda unidad. Si usted activa la unidad, systemd la activa solo después de la segunda. Por ejemplo, el servicio
foo
podría requerir conectividad de red, lo que significa que el serviciofoo
especificanetwork.target
como una condiciónAfter=
.La sección
[Unit]
resultante se ve como esto:[Unit] Description=My custom service After=network.target
-
La sección
[Service]
proporciona instrucciones sobre como controlar el servicio. El servicio`foo` utiliza los siguientes parámetros:Type
-
Define el tipo de servicio systemd. En este ejemplo, el servicio
foo
es un serviciosimple
, el cual inicia el servicio sin ninguna consideración especial. ExecStart
-
El comando para ejecutar el inicio del servicio. Esto incluye la ruta completa al comando y los argumentos que modifican el servicio.
La sección
[Service]
resultante se parece a esto:[Service] Type=simple ExecStart=/usr/bin/sleep infinity
-
La sección
[Install]
proporciona instrucciones sobre como systemd instala el servicio.. El serviciofoo
usa los siguientes parámetros:WantedBy
-
Define que servicio dispara el servicio personalizado si está habilitado con
systemctl enable
. Esto se utiliza mayormente para iniciar el servicio personalizado en el arranque. En este ejemplo,foo.service
usamulti-user.target
, el cual inicia`foo.service` cuando systemd cargamulti-user.target
en el arranque.
-
-
El archivo completo`foo.service` tiene los siguientes contenidos:
[Unit] Description=My custom service After=network.target [Service] Type=simple ExecStart=/usr/bin/sleep infinity [Install] WantedBy=multi-user.target
Guarde el archivo.
-
Para hacer que systemd esté atento al nuevo servicio, recargue sus archivos de servicio
# systemctl daemon-reload
-
Inicie el servicio personalizado
foo
:# systemctl start foo
-
Verifique el estado del servicio para asegurar que el servicio está corriendo:
$ systemctl status foo ● foo.service - My custom service Loaded: loaded (/etc/systemd/system/foo.service; static; vendor preset: disabled) Active: active (running) since Thu 2017-12-14 14:09:12 AEST; 6s ago Main PID: 31837 (sleep) Tasks: 1 (limit: 4915) CGroup: /system.slice/foo.service └─31837 /usr/bin/sleep infinity Dec 14 14:09:12 dansmachine systemd[1]: Started My custom service.
Información Relacionada
-
Vea Parámetros comunes de servicio para más información sobre los parámetros de este procedimiento.
Converting SysVinit services to systemd
Older versions of Fedora use SysVinit scripts to manage services. This section provides some guidelines on how to convert a SysVinit script to a systemd equivalent.
Requisitos previos
-
Usted tiene que acceder con un usuario con permisos a nivel de administrador.
-
You have a custom SysVinit script to convert to a systemd configuration.
Procedimiento
-
Identify the runlevels in your SysVinit script. This is usually defined with
chkconfig
directive in the commented section at the beginning of the script. For example, the following indicates the service is using runlevels 3, 4, and 5:# chkconfig: 235 20 80
systemd uses targets instead of runlevels. Use the table in [converting-sysvinit-services] to map the runlevels to targets. In this example, runlevels 2, 3, and 5 are all multi-user runlevels, so the systemd service can use the following:
[Install] WantedBy=multi-user.target
If you enable the custom systemd service to start at boot (
systemctl enable foo.service
), systemd loads the service when loading themulti-user.target
at boot time. -
Identify the dependent services and targets. For example, if the custom service requires network connectivity, specify the
network.target
as a dependency:[Unit] Description=My custom service After=network.target
-
Identify the command used to start the service in the SysVinit script and convert this to the systemd equivalent. For example, the script might contain a
start
function in the following format:start() { echo "Starting My Custom Service..." /usr/bin/myservice -D }
In this example, the
/usr/bin/myservice
command is the custom service command set to daemonize with the-D
option. Set theExecStart
parameter to use this command:[Service] ExecStart=/usr/bin/myservice -D
-
Check the SysVinit script to see if the service uses a special command to restart the service. For example, the script might contain a
reboot
function that reloads the service:reboot() { echo "Reloading My Custom Service..." /usr/bin/myservice reload }
In this example, the
/usr/bin/myservice
command is the custom service command and reloads the service using thereload
subcommand. Set theExecReload
parameter to use this command:[Service] ExecReload=/usr/bin/myservice reload
Alternatively, you can omit
ExecReload
and use the default behavior, which kills the service and starts it again. -
Check the SysVinit script to see if the service uses a special command to stop the service. For example, the script might contain a
stop
function that reloads the service:reboot() { echo "Stopping My Custom Service..." /usr/bin/myservice shutdown }
In this example, the
/usr/bin/myservice
command is the custom service command and stop the service gracefully using theshutdown
subcommand. Set theExecStop
parameter to use this command:[Service] ExecStop=/usr/bin/myservice shutdown
Alternatively, you can omit
ExecStop
and use the default behavior, which kills the service. -
Review the SysVinit script and identify any additional parameters or functions. Use systemd parameters to replicate any identified SysVinit functions that might be relevant to your service.
Información Relacionada
-
Vea Parámetros comunes de servicio para más información sobre los parámetros de este procedimiento.
Common service parameters
Unit Parameters
This section contains parameters you can use in the [Unit]
section of a service. These parameters are common to other systemd units.
This list is a summarized version. For a full list of these parameters and their descriptions, run man systemd.unit
.
- Description
-
A free-form string describing the service.
- Documentation
-
A space-separated list of URIs referencing documentation for this service or its configuration. Accepted are only URIs of the following types:
http://
,https://
,file:
,info:
,man:
. - Requires
-
Configures requirement dependencies on other services. If this service gets activated, the units listed here are activated too. If one of the dependent services fails to activate, systemd does not start this service. This option may be specified more than once or you can specify multiple space-separated units.
- Wants
-
Similar to
Requires
, except failed units do not have any effect on the service. - BindsTo
-
Similar to
Requires
, except stopping the dependent units also stops the service. - PartOf
-
Similar to
Requires
, except the stopping and restarting dependent units also stop and restart the service. - Conflicts
-
A space-separated list of unit names that, if running, cause the service not to run.
- Before, After
-
A space-separated list of unit names that configures the ordering of dependencies between services.
- OnFailure
-
A space-separated list of unit names that are activated when this service enters a failed state.
Install Parameters
This section contains parameters you can use in the [Install]
section of a service. These parameters are common to other systemd units.
This list is a summarized version. For a full list of these parameters and their descriptions, run man systemd.unit
.
- Alias
-
A space-separated list of additional names this service shall be installed under. The names listed here must have the same suffix (i.e. type) as the service filename.
- RequiredBy, WantedBy
-
Defines the service as dependent of another service. This usually define the target to trigger an enabled service to run. These options are analogous to the
Requires
andWants
in the[Units]
section. - Also
-
Additional units to install or uninstall when this service is installed or uninstalled.
Service Parameters
This section contains parameters you can use in the [Service]
section of a service unit. These parameters are specific only to systemd service units.
This list is a summarized version. For a full list of these parameters and their descriptions, run man systemd.unit
.
- Type
-
Configures the process start-up type for this service service:
-
simple
- The service starts as the main process. This is the default. -
forking
- The service calls forked processes and run as part of the main daemon. -
oneshot
- Similar tosimple
, except the process must exit before systemd starts follow-up services. -
dbus
- Similar tosimple
, except the daemon acquires a name of the D-Bus bus. -
notify
- Similar tosimple
, except the daemon sends a notification message usingsd_notify
or an equivalent call after starting up. -
idle
- Similar tosimple
, except the execution of the service is delayed until all active jobs are dispatched.
-
- RemainAfterExit
-
A boolean value that specifies whether the service shall be considered active even if all its processes exited. Defaults to no.
- GuessMainPID
-
A boolean value that specifies whether systemd should guess the main PID of a service if it cannot be determined reliably. This option is ignored unless
Type=forking
is set andPIDFile
is not set. Defaults to yes. - PIDFile
-
An absolute filename pointing to the PID file of this daemon. Use of this option is recommended for services where
Type=forking
. Systemd reads the PID of the main process of the daemon after start-up of the service. Systemd does not write to the file configured here, although it removes the file after the service has shut down. - BusName
-
A D-Bus bus name to reach this service. This option is mandatory for services where
Type=dbus
. - ExecStart
-
The commands and arguments executed when the service starts.
- ExecStartPre, ExecStartPost
-
Additional commands that are executed before or after the command in
ExecStart
. - ExecReload
-
The commands and arguments to execute when the service reloads.
- ExecStop
-
The commands and arguments to execute when the service stops.
- ExecStopPost
-
Additional commands to execute after the service stops.
- RestartSec
-
The time in seconds to sleep before restarting a service.
- TimeoutStartSec
-
The time in seconds to wait for the service to start.
- TimeoutStopSec
-
The time in seconds to wait for the service to stop.
- TimeoutSec
-
A shorthand for configuring both
TimeoutStartSec
andTimeoutStopSec
simultaneously. - RuntimeMaxSec
-
A maximum time in seconds for the service to run. Pass
infinity
(the default) to configure no runtime limit. - Restart
-
Configures whether to restart the service when the service’s process exits, is killed, or reaches a timeout:
-
no
- The service will not be restarted. This is the default. -
on-success
- Restart only when the service process exits cleanly (exit code 0). -
on-failure
- Restart only when the service process does not exit cleanly (node-zero exit code). -
on-abnormal
- Restart if the process terminates with a signal or when a timeout occurs. -
on-abort
- Restart if the process exits due to an uncaught signal not specified as a clean exit status. -
always
- Always restart.
-
Mapeo de niveles de ejecución a objetivos
Los objetivos Systemd sirven a un propósito similar que los niveles de ejecución SysVinit pero actúan un poco diferente. Cada objetivo tiene un nombre en lugar de un número y cada uno sirve a un propósito específico. Systemd implementa algunos objetivos heredando todos los servicios de otro objetivo y añadiéndole servicios adicionales. Algunos objetivos systemd imitan los niveles de ejecución comunes de sysvinit, lo que significa que puede cambiar de objetivo con el familiar comando telinit RUNLEVEL
. Los niveles de ejecución que asignaron un propósito específico en las instalaciones básicas de Fedora (0, 1, 3, 5 y 6) tienen un mapeo 1:1 con un objetivo específico systemd.
Sin embargo, este no es el caso de los niveles de ejecución definidos por el usuario 2 y 4. Para hacer uso de estos niveles de ejecución, cree un nuevo objetivo systemd con un nombre como /etc/systemd/system/$YOURTARGET`que toma uno de los niveles de ejecución existentes como base haga un directorio `/etc/systemd/system/$YOURTARGET.wants
y después un enlace simbólico a los servicios adicionales para habilitar este directorio.
Los siguiente es un mapeo de los niveles de ejecución SysVinit a los objetivos systemd.
Nivel de ejecución Sysvinit | Objetivo systemd | Notas |
---|---|---|
0 |
runlevel0.target, poweroff.target |
Para el sistema. |
1, s, single |
runlevel1.target, rescue.target |
Modo usuarios único. |
2, 4 |
runlevel2.target, runlevel4.target, multi-user.target |
Definido por el usuario/Niveles de ejecución específicos del sitio. Predeterminado, idéntico a 3. |
3 |
runlevel3.target, multi-user.target |
Multi-user, non-graphical. Los usuarios pueden acceder normalmente por medio de múltiples consolas o por red. |
5 |
runlevel5.target, graphical.target |
Multiusuario, gráfico. Normalmente tiene todos los servicios del nivel de ejecución 3 más acceso gráfico. |
6 |
runlevel6.target, reboot.target |
Reinicio |
emergency |
emergency.target |
Shell de emergencia |
Mapping service commands
The following table demonstrates the systemd equivalent of SysVinit commands.
All recent versions of systemctl assume the .service suffix if left off the service name. For example, systemctl start frobozz.service is the same as systemctl start frobozz .
|
Sysvinit Command | systemd Command | Notes |
---|---|---|
|
|
Used to start a service (not reboot persistent) |
|
|
Used to stop a service (not reboot persistent) |
|
|
Used to stop and then start a service |
|
|
When supported, reloads the config file without interrupting pending operations. |
|
|
Restarts if the service is already running. |
|
|
Tells whether a service is currently running. |
|
|
Used to list the services that can be started or stopped |
|
|
Turn the service on, for start at next boot, or other trigger. |
|
|
Turn the service off for the next reboot, or any other trigger. |
|
|
Used to check whether a service is configured to start or not in the current environment. |
|
|
Print a table of services that lists which runlevels each is configured on or off |
|
|
Print a table of services that will be started when booting into graphical mode |
|
|
Used to list what levels this service is configured on or off |
|
|
Used when you create a new service file or modify any configuration |
All /sbin/service and /sbin/chkconfig commands listed in the table continue to work on systemd-based systems and are translated to native equivalents as necessary. The only exception is chkconfig --list .
|
Recursos Adicionales
-
Lennart Poettering’s blog with lots of information about systemd. Lennart is the primary systemd developer
Want to help? Learn how to contribute to Fedora Docs ›