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.servicePaste 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.targetConfiguration Breakdown:
- After=network.target: Ensures the service only starts after the network is fully available.
- ExecStart: The absolute path to the FFmpeg binary
followed by your arguments. (Use
which ffmpegin your terminal to find your exact path). - Restart=always: Automatically restarts FFmpeg if the process terminates or crashes.
- RestartSec=5: Waits 5 seconds before attempting a restart.
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-reloadStep 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.serviceTo enable the service to start on system boot:
sudo systemctl enable ffmpeg-stream.serviceStep 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.serviceTo view the live output and logs generated by FFmpeg, use
journalctl:
sudo journalctl -u ffmpeg-stream.service -fManaging the Service
To stop or restart your background process at any time, use the following standard systemd commands:
- Stop the service:
sudo systemctl stop ffmpeg-stream.service - Restart the service:
sudo systemctl restart ffmpeg-stream.service