One easy approach is to use systemd. You should note that at the startup the environment variables like JAVA_HOME are not loaded yet, so we should introduce them to the system. One good solution is to create a file named profile
and add all the necessary variable to that:
# /home/kafka/profile
JAVA_HOME=/opt/jdk8
KAFKA_HOME=/opt/kafka
Supposing you've installed Kafka on the path /opt/kafka
, in order to Kafka run automatically after Ubuntu startup (tested on Ubuntu 16.04 and centOS7 and I guess it works on any distribution with the support of the systemd) do the following command:
sudo nano /etc/systemd/system/kafka.service # open file to add service informations
Now add the following contents to the file
[Unit]
Description=Kafka Daemon
Wants=syslog.target
# suppose you have a service named zookeeper that it start zookeeper and we want Kafka service run after the zookeeper service
After=zookeeper.service
[Service]
Type=forking
# the user whom you want run the Kafka start and stop command under
User=kafka
# the file path that contains envirnment variables
EnvironmentFile=/home/kafka/profile
# the directory that the commands will run there
WorkingDirectory=/home/kafka/
# Kafka server start command
ExecStart=/opt/kafka/bin/kafka-server-start.sh -daemon /opt/kafka/config/server.properties
# Kafka server stop command
ExecStop=/opt/kafka/bin/kafka-server-stop.sh -daemon
TimeoutSec=30
Restart=on-failure
[Install]
WantedBy=multi-user.target
Note: As Kafka need the zookeeper to connect it at the starting time, I supposed we have a zookeeper service too and I set the Kafka service to run after zookeeper service starting.
Now after saving the kafka.service
file, just run the following command to create a link of the Kafka service and it will start every time you reboot the OS:
sudo systemctl enable kafka
Now you can start the Kafka service using the command:
sudo systemctl start kafka.service
and check the status of the service:
sudo systemctl status kafka.service