Comando Linux systemctl
Manual completo de comandos Linux
Qué es systemctl
systemctl es una herramienta de línea de comandos en el sistema Linux que se utiliza para controlar systemd, el sistema y gestor de servicios. Como componente central de las distribuciones Linux modernas, sustituye al sistema init tradicional y al comando service.
Introducción a systemd
systemd es un administrador del sistema y de servicios que:
- Se ejecuta como PID 1 (el primer proceso que se inicia)
- Se encarga de iniciar, detener y gestionar todos los demás procesos
- Ofrece capacidad de inicio paralelo, acelerando significativamente la velocidad de arranque del sistema
- Admite el inicio de servicios bajo demanda
- Proporciona funciones de recopilación de registros (a través de journald)
Sintaxis básica de systemctl
systemctl [选项] [命令] [单元名称]
Opciones comunes
| Opción | Descripción |
|---|---|
| -t, --type | Especifica el tipo de unidad (service, socket, device, etc.) |
| -a, --all | Muestra todas las unidades, incluyendo las inactivas |
| --state | Filtra las unidades por estado |
| -l, --full | Muestra información completa de la unidad |
| -H, --host | Opera en un host remoto |
Comandos de gestión de servicios
Iniciar/detener/reiniciar servicios
Ejemplo
# Iniciar servicio
sudo systemctl start [nombre-del-servicio]
# Detener servicio
sudo systemctl stop [nombre-del-servicio]
# Reiniciar servicio
sudo systemctl restart [nombre-del-servicio]
# Recargar la configuración (sin reiniciar el servicio)
sudo systemctl reload [nombre-del-servicio]
sudo systemctl start [nombre-del-servicio]
# Detener servicio
sudo systemctl stop [nombre-del-servicio]
# Reiniciar servicio
sudo systemctl restart [nombre-del-servicio]
# Recargar la configuración (sin reiniciar el servicio)
sudo systemctl reload [nombre-del-servicio]
Ver el estado del servicio
Ejemplo
# Ver el estado de un solo servicio
systemctl status [nombre-del-servicio]
# Ver todos los servicios en ejecución
systemctl list-units --type=service --state=running
# Ver los servicios con fallos
systemctl --failed
systemctl status [nombre-del-servicio]
# Ver todos los servicios en ejecución
systemctl list-units --type=service --state=running
# Ver los servicios con fallos
systemctl --failed
Habilitar/deshabilitar servicios
Ejemplo
# Habilitar servicio (inicio automático al arrancar)
sudo systemctl enable [nombre-del-servicio]
# Deshabilitar servicio (cancelar inicio automático al arrancar)
sudo systemctl disable [nombre-del-servicio]
# Ver si el servicio está habilitado
systemctl is-enabled [nombre-del-servicio]
sudo systemctl enable [nombre-del-servicio]
# Deshabilitar servicio (cancelar inicio automático al arrancar)
sudo systemctl disable [nombre-del-servicio]
# Ver si el servicio está habilitado
systemctl is-enabled [nombre-del-servicio]
Gestión de archivos de unidad
Ubicación de los archivos de unidad
- Unidades del sistema:
/usr/lib/systemd/system/ - Unidades personalizadas por el administrador:
/etc/systemd/system/
Operaciones comunes con archivos de unidad
Ejemplo
# Recargar todos los archivos de unidad (se debe ejecutar después de modificar la configuración)
sudo systemctl daemon-reload
# Mostrar el contenido del archivo de unidad
systemctl cat [nombre-de-la-unidad]
# Editar el archivo de unidad (se creará un archivo de anulación)
sudo systemctl edit [nombre-de-la-unidad] --full
sudo systemctl daemon-reload
# Mostrar el contenido del archivo de unidad
systemctl cat [nombre-de-la-unidad]
# Editar el archivo de unidad (se creará un archivo de anulación)
sudo systemctl edit [nombre-de-la-unidad] --full
Gestión del estado del sistema
Gestión de energía del sistema
Ejemplo
# Apagar
sudo systemctl poweroff
# Reiniciar
sudo systemctl reboot
# Suspender
sudo systemctl suspend
# Hibernar
sudo systemctl hibernate
sudo systemctl poweroff
# Reiniciar
sudo systemctl reboot
# Suspender
sudo systemctl suspend
# Hibernar
sudo systemctl hibernate
Niveles de ejecución del sistema
Ejemplo
# Obtener el objetivo actual (nivel de ejecución)
systemctl get-default
# Establecer el objetivo predeterminado
sudo systemctl set-default [nombre-del-objetivo]
# Cambiar de objetivo (efecto inmediato)
sudo systemctl isolate [nombre-del-objetivo]
systemctl get-default
# Establecer el objetivo predeterminado
sudo systemctl set-default [nombre-del-objetivo]
# Cambiar de objetivo (efecto inmediato)
sudo systemctl isolate [nombre-del-objetivo]
Objetivos comunes:
- graphical.target - Modo de interfaz gráfica
- multi-user.target - Modo de texto multiusuario
- rescue.target - Modo de rescate
- emergency.target - Modo de emergencia
Ejemplos prácticos
Ejemplo 1: Administrar el servicio Nginx
Ejemplo
# Iniciar Nginx
sudo systemctl start nginx
# Configurar el inicio automático al arrancar
sudo systemctl enable nginx
# Comprobar el estado
systemctl status nginx
# Recargar después de probar la configuración
sudo nginx -t # Probar primero la configuración
sudo systemctl reload nginx
sudo systemctl start nginx
# Configurar el inicio automático al arrancar
sudo systemctl enable nginx
# Comprobar el estado
systemctl status nginx
# Recargar después de probar la configuración
sudo nginx -t # Probar primero la configuración
sudo systemctl reload nginx
Ejemplo 2: Crear un servicio personalizado
- Crear el archivo de servicio
/etc/systemd/system/myapp.service:
Ejemplo
[Unit]
Description=My Custom Application
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/myapp/app.py
WorkingDirectory=/opt/myapp
User=myappuser
Group=myappgroup
Restart=always
[Install]
WantedBy=multi-user.target
Description=My Custom Application
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/myapp/app.py
WorkingDirectory=/opt/myapp
User=myappuser
Group=myappgroup
Restart=always
[Install]
WantedBy=multi-user.target
- Habilitar e iniciar el servicio:
Ejemplo
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl enable myapp
sudo systemctl start myapp
Solución de problemas comunes
Fallo al iniciar el servicio
Ver los registros detallados:
journalctl -u [服务名] -xe
Verificar las dependencias:
systemctl list-dependencies [服务名]
Ejecutar en modo de depuración:
systemctl status [服务名] -l --no-pager
Análisis de rendimiento
Ejemplo
# Mostrar el tiempo de arranque del sistema
systemd-analyze
# Mostrar el tiempo de inicio de cada servicio
systemd-analyze blame
# Generar el diagrama de flujo de arranque (requiere interfaz gráfica)
systemd-analyze plot > boot.svg
systemd-analyze
# Mostrar el tiempo de inicio de cada servicio
systemd-analyze blame
# Generar el diagrama de flujo de arranque (requiere interfaz gráfica)
systemd-analyze plot > boot.svg