CentOS 7下用systemd创建无ExecStop的Kafka独立生产者服务并正常停止
Got it, let's tackle this problem. The core issue here is that your Kafka File Connector (standalone producer) is a foreground process that only responds to Ctrl+C (SIGINT signal) to terminate, but systemd defaults to sending SIGTERM when you run systemctl stop—which the process doesn't handle properly. You don't need a custom ExecStop script; we can just configure systemd to send the right signal instead.
Step-by-Step Implementation
1. Create the systemd Service File
First, create a service file at /etc/systemd/system/kafka-file-connector.service with the following content. Adjust paths, user, and group to match your actual environment:
[Unit] Description=Kafka File Source Connector (Standalone) After=network.target kafka.service zookeeper.service Requires=kafka.service zookeeper.service [Service] User=kafka Group=kafka Type=simple WorkingDirectory=/opt/kafka ExecStart=/opt/kafka/bin/connect-standalone.sh /opt/kafka/config/connect-standalone.properties /opt/kafka/config/file-source.properties # Send SIGINT (same as Ctrl+C) instead of systemd's default SIGTERM KillSignal=SIGINT # Optional: Auto-restart the connector if it crashes unexpectedly Restart=on-failure RestartSec=5 # Redirect logs to journald for easy viewing StandardOutput=journal+console StandardError=journal+console [Install] WantedBy=multi-user.target
2. Reload systemd and Start the Service
Run these commands to apply the new service configuration and start the connector:
sudo systemctl daemon-reload sudo systemctl start kafka-file-connector
3. Verify and Test the Service
Check if the service is running correctly:
sudo systemctl status kafka-file-connector
Test stopping the service—this should now work smoothly, just like pressing Ctrl+C in the foreground:
sudo systemctl stop kafka-file-connector
Why This Works
- By default, systemd sends the
SIGTERMsignal to stop processes. However, many Java-based applications (like Kafka connectors) aren't configured to handleSIGTERMgracefully, but they do respond toSIGINT(the signal triggered by Ctrl+C). - Setting
KillSignal=SIGINTtells systemd to use that signal instead of the default, which mimics the manual termination method you relied on before. - We don't need an
ExecStopdirective because systemd handles sending the correct signal automatically.
Optional Tips
- To make the connector start automatically on system boot:
sudo systemctl enable kafka-file-connector - View real-time logs for troubleshooting:
journalctl -u kafka-file-connector -f
内容的提问来源于stack exchange,提问作者WesternGun

