Skip to Content
문서운영시스템 관리시스템화 및 서비스 관리

systemd 및 서비스 관리

26.10 버전 차이

26.10은 systemd 261.3를 사용하고 systemd-sysv-generator을 제거합니다. 사용자 정의 /etc/init.d 스크립트는 더 이상 생성된 서비스에 의존할 수 없습니다. 기본 systemd 장치로 마이그레이션하고 시작, 중지, 다시 시작 및 부팅 활성화를 테스트합니다. 공식 릴리스 노트 

systemd은 Ubuntu 26.04의 초기화 시스템 및 서비스 관리자로, 시스템 부트스트래핑, 서비스 및 데몬 관리를 담당합니다. systemd을 마스터하는 것은 Ubuntu 시스템 관리에 필수적인 기술입니다.

systemctl 기본 사항

서비스 상태 관리

# 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

부팅 서비스 관리

# 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

서비스 정보 보기

# 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

서비스 단위 파일

단위 파일 위치

systemd 서비스 단위 파일은 우선 순위(가장 높은 것에서 가장 낮은 것)에 따라 다음 위치에 저장됩니다.

길설명
/etc/systemd/system/맞춤 관리 구성, 최우선 순위
/run/systemd/system/런타임 생성 유닛 파일
/lib/systemd/system/패키지에 의해 설치되는 기본 유닛 파일

유닛 파일 보기

# 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

단위 파일 구조

일반적인 서비스 단위 파일에는 세 가지 섹션이 있습니다.

[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

일반적인 서비스 유형

유형설명
simple기본; ExecStart에 의해 시작된 프로세스가 주 프로세스입니다.
forking서비스는 하위 프로세스를 분기합니다. 부모가 종료되면 시작은 완료된 것으로 간주됩니다.
oneshot일회성 작업 프로세스가 종료되면 완료된 것으로 간주됩니다.
notify서비스는 시작이 완료되면 sd_notify를 통해 systemd에 알립니다.
idle간단하지만 시작하기 전에 다른 작업이 완료될 때까지 기다립니다.

정책 다시 시작

옵션설명
no자동으로 다시 시작하지 않음(기본값)
on-success정상 종료 시 다시 시작
on-failure비정상 종료 시 다시 시작
on-abnormal신호 또는 시간 초과로 인해 종료되면 다시 시작
on-abort잡히지 않은 신호에 의해 종료되면 다시 시작
always종료 이유에 관계없이 항상 다시 시작

맞춤형 서비스 생성

예: Node.js 애플리케이션 서비스

유닛 파일을 생성합니다:

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

다음 콘텐츠를 추가합니다.

[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

서비스를 활성화하고 시작합니다.

# 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

예: 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

예: 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

재정의를 사용하여 기존 서비스 수정

/lib/systemd/system/의 파일을 직접 수정하는 것은 권장되지 않습니다. 대신 재정의를 사용하세요.

# Create an override file sudo systemctl edit nginx.service

그러면 구성 재정의를 추가할 수 있는 편집기가 열립니다.

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

재정의 파일은 /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

시스템 관리 명령

# 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

자원 제한

서비스 단위 파일에서 리소스 제한을 설정할 수 있습니다.

[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

문제 해결

# 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

관련 기사