Question: How to do set environment variables for use with a systemd service of MySQL Server?
There are a number of different methods that can be used to set environment variables for a systemd service. The method used can vary depending on the Linux distribution and the version of the distribution. The MySQL manual states the service setup is done simply as (example only):
[Service] LimitNOFILE=max_open_files PIDFile=/path/to/pid/file Nice=nice_level LimitCore=core_file_limit
Method 1 – Using ‘systemd edit’
This is the preferred method which is to create and/or edit an override file that contains the environment variables. The command to create/edit the override file is:
# systemctl edit mysqld
This will then create a directory (if not existing) and create an override.conf file which will contain the variables. e.g
[Service] Environment="TZ=time_zone_setting" Environment="AUTHENTICATION_PAM_LOG=1" Environment="LD_PRELOAD=/path/to/malloc/library"
The override file and directory will usually be: /etc/systemd/system/mysqld.service.d/override.conf
Method 2 – Add multiple variables via a file
This method allows multiple environment variables to be added to the service via a simple file.
[Service] LimitNOFILE=max_open_files PIDFile=/path/to/pid/file Nice=nice_level LimitCore=core_file_limit EnvironmentFile=-/etc/sysconf/mysqld
The ‘–‘ character at the start of the EnvironmentFile value is to let systemd ignore errors if the file does not exist. The environment file will simply have the list of different variables in the name=value format. For example:
LD_PRELOAD=/path/to/malloc/library TZ=time_zone_setting AUTHENTICATION_PAM_LOG=1
The environment file can be any, as defined by the EnvironmentFile attribute in the service, however, it could be specific to the version and distribution of Linux. Some older versions will expect it to be in /etc/sysconf (for Redhat-based distributions) versus /etc/default (for Debian-based distributions). This is the method currently used by the Oracle MySQL packages.
Method 3 – Add the environment variable directly
This is simply to add a name=value setting into the [Service] are of the mysql service file.
[Service] LimitNOFILE=max_open_files PIDFile=/path/to/pid/file Nice=nice_level LimitCore=core_file_limit Environment="LD_PRELOAD=/path/to/malloc/library"
The ‘Environment‘ keyword here is used to identify what environment variable is specified. In the setting above, the environment variable is defined to use a different malloc library for the MySQL Server.