Managing environment variables is crucial for configuring services on Linux. Depending on whether you are using systemd or init.d scripts to manage your services, the methods for setting environment variables differ slightly. This guide explores how to set environment variables in both systemd and init.d, providing flexibility and customization options for your services.
Using systemd
Systemd is the modern init system used by many Linux distributions. It offers robust management of services and provides a straightforward way to handle environment variables.
Creating or Editing a systemd Service Unit File:
- Location:
/etc/systemd/system/
or/lib/systemd/system/
- Example:
myservice.service
Defining Environment Variables: - Inside the
[Service]
section, use theEnvironment
directive to set variables:
[Service]
Environment="ENV_VAR1=value1"
Environment="ENV_VAR2=value2"
- Multiple variables can be defined by adding more
Environment
lines.
Applying Changes: - Reload systemd to apply the new configuration:
sudo systemctl daemon-reload
- Restart your service to pick up the updated environment variables:
sudo systemctl restart myservice
Using init.d
Init.d scripts are traditional Unix-style init scripts commonly found on older Linux systems. Setting environment variables in init.d scripts involves direct assignment within the script itself.
Editing Your Init Script:
- Location:
/etc/init.d/
- Example:
myservice
Setting Environment Variables: - Directly assign values before starting your service:
!/bin/bash
export ENV_VAR1=value1
export ENV_VAR2=value2
Commands to manage your service
case "$1" in
start)
/path/to/your/service start
;;
stop)
/path/to/your/service stop
;;
restart)
/path/to/your/service restart
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac
exit 0
Making the Script Executable:
- Ensure your script has executable permissions:
sudo chmod +x /etc/init.d/myservice
Managing Your Service:
- Use standard init script commands to manage your service:
sudo /etc/init.d/myservice start
sudo /etc/init.d/myservice stop
sudo /etc/init.d/myservice restart
Conclusion
Both systemd and init.d offer effective ways to manage environment variables for Linux services. Systemd provides a structured approach through service unit files, while init.d scripts allow direct customization within the script itself. Choose the method that best suits your distribution and service management preferences to ensure smooth operation and configuration of your applications.