Best Practices for MySQL Environment Variables

Setting up environment variables for MySQL is crucial for securing database credentials, simplifying command-line access, and streamlining application deployment. This guide covers the best practices for configuring these variables, focusing on security, system path integration, and automation across different operating systems.

1. Add MySQL to the System PATH for Easy Access

To run MySQL commands from any terminal window without typing the full directory path, add the MySQL bin directory to your system’s PATH variable.

2. Avoid Using the MYSQL_PWD Variable

While MySQL supports the MYSQL_PWD environment variable to automatically log you in, using it is highly discouraged.

On Unix-like systems, environment variables can be viewed by other users running command-line utilities like ps. Storing your database password in MYSQL_PWD exposes your credentials to anyone with access to the server command line.

The Secure Alternative: mysql_config_editor

Instead of using variables for passwords, use the built-in mysql_config_editor tool. This utility creates an obfuscated login path file (.mylogin.cnf) that allows secure passwordless logins.

mysql_config_editor set --login-path=local --host=localhost --user=root --password

You can then log in securely using:

mysql --login-path=local

3. Use Standardized Naming Conventions for Applications

When connecting applications to your MySQL database, use standardized, uppercase environment variable names. This maintains consistency across development, staging, and production environments. Recommended names include:

4. Secure .env Files in Development

In local development environments, developer tools often read environment variables from a .env file. To keep this file secure:

5. Leverage Secrets Managers in Production

In production environments, avoid storing MySQL connection details in plain-text OS environment files. Instead, inject variables dynamically using a cloud-native secret manager or container orchestration tool: