How to Run FFmpeg in the Background with systemd

This article provides a straightforward guide on how to configure and run FFmpeg as a continuous background service on Linux using systemd. You will learn how to create a systemd service file, start and enable the service on boot, and monitor its output logs. This approach ensures your media transcoding or streaming tasks remain resilient, automatically restarting if they crash or when the system reboots.

Step 1: Create the systemd Service File

To manage FFmpeg with systemd, you must create a service configuration file. Open a terminal and create a new file in the systemd directory using a text editor like nano:

sudo nano /etc/systemd/system/ffmpeg-stream.service

Paste the following configuration into the file. Customize the ExecStart line with your specific FFmpeg command:

[Unit]
Description=FFmpeg Background Streaming Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/ffmpeg -re -i rtsp://your-input-stream -c:v copy -c:a aac -f flv rtmp://your-output-destination
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Configuration Breakdown:

Save and close the file (in nano, press Ctrl+O, Enter, then Ctrl+X).

Step 2: Reload the systemd Daemon

For systemd to recognize your new service file, you must reload the systemd manager configuration:

sudo systemctl daemon-reload

Step 3: Start and Enable the Service

Now you can start the FFmpeg service and configure it to launch automatically whenever the system boots.

To start the service immediately:

sudo systemctl start ffmpeg-stream.service

To enable the service to start on system boot:

sudo systemctl enable ffmpeg-stream.service

Step 4: Verify and Monitor the Service

To check if your FFmpeg service is running successfully without errors, use the status command:

sudo systemctl status ffmpeg-stream.service

To view the live output and logs generated by FFmpeg, use journalctl:

sudo journalctl -u ffmpeg-stream.service -f

Managing the Service

To stop or restart your background process at any time, use the following standard systemd commands: