Set up development database environments with environment variables

Beginner 25 min May 06, 2026 63 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Learn to configure PostgreSQL, MySQL, and MariaDB development databases using environment variables for secure connection management and simplified configuration across different environments.

Prerequisites

  • Root or sudo access
  • Basic command line knowledge

What this solves

Managing database connections across development environments becomes complex when hardcoding credentials in application code. Environment variables provide a secure, flexible way to configure database connections that works across local development, testing, and staging environments. This approach separates configuration from code and prevents accidental credential exposure in version control.

Environment variables overview and best practices

Environment variables store configuration values outside your application code, making them accessible to running processes. For database configurations, they typically include connection strings, usernames, passwords, host addresses, and port numbers.

Create environment configuration directory

Set up a dedicated directory for your development environment configurations.

mkdir -p ~/dev-config/database-envs
cd ~/dev-config/database-envs

Create base environment template

Create a template file that defines standard database environment variables.

# Database Configuration Template

PostgreSQL

POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_DB=devdb POSTGRES_USER=devuser POSTGRES_PASSWORD=secure_password_here DATABASE_URL=postgresql://devuser:secure_password_here@localhost:5432/devdb

MySQL/MariaDB

MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=devdb MYSQL_USER=devuser MYSQL_PASSWORD=secure_password_here MYSQL_ROOT_PASSWORD=root_password_here

Application Settings

ENVIRONMENT=development DEBUG=true LOG_LEVEL=debug

Set secure file permissions

Environment files often contain sensitive credentials and should be readable only by the file owner.

chmod 600 .env.template
echo ".env*" >> ~/.gitignore
Never commit .env files. Environment files contain sensitive credentials that should never be stored in version control. Always add them to .gitignore.

PostgreSQL development environment setup

Install PostgreSQL server

Install PostgreSQL database server and client tools for development use.

sudo apt update
sudo apt install -y postgresql postgresql-contrib postgresql-client
sudo dnf install -y postgresql postgresql-server postgresql-contrib
sudo postgresql-setup --initdb

Start and enable PostgreSQL

Enable PostgreSQL to start automatically and start the service now.

sudo systemctl enable --now postgresql
sudo systemctl status postgresql

Create development database and user

Set up a dedicated database and user for development work with appropriate permissions.

sudo -u postgres createuser --interactive --pwprompt devuser
sudo -u postgres createdb -O devuser devdb

When prompted, enter a secure password for the devuser account and answer 'n' to superuser, database creation, and role creation prompts.

Configure PostgreSQL authentication

Update PostgreSQL configuration to allow password authentication for development.

sudo cp /etc/postgresql//main/pg_hba.conf /etc/postgresql//main/pg_hba.conf.backup

Edit the authentication configuration file:

# Add this line after the existing local connections
local   devdb           devuser                                 md5
host    devdb           devuser         127.0.0.1/32            md5
host    devdb           devuser         ::1/128                 md5
sudo systemctl reload postgresql

Create PostgreSQL environment file

Create a specific environment configuration for your PostgreSQL development setup.

POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=devdb
POSTGRES_USER=devuser
POSTGRES_PASSWORD=your_secure_password
DATABASE_URL=postgresql://devuser:your_secure_password@localhost:5432/devdb
ENVIRONMENT=development
chmod 600 .env.postgres

Test PostgreSQL connection with environment variables

Verify the connection works by loading environment variables and connecting to the database.

set -a; source .env.postgres; set +a
psql "$DATABASE_URL" -c "SELECT version();"
psql "$DATABASE_URL" -c "\dt"

MySQL and MariaDB configuration with environment variables

Install MariaDB server

Install MariaDB as a drop-in replacement for MySQL with better performance and licensing.

sudo apt update
sudo apt install -y mariadb-server mariadb-client
sudo dnf install -y mariadb-server mariadb

Start and enable MariaDB

Enable MariaDB to start automatically and start the service now.

sudo systemctl enable --now mariadb
sudo systemctl status mariadb

Secure MariaDB installation

Run the security script to set root password and remove insecure defaults.

sudo mysql_secure_installation

Follow the prompts to set a root password, remove anonymous users, disable remote root login, and remove the test database. Answer 'Y' to all security questions.

Create development database and user

Create a dedicated database and user for development with limited privileges.

sudo mysql -u root -p
CREATE DATABASE devdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'devuser'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON devdb.* TO 'devuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Create MariaDB environment file

Create environment configuration for MariaDB development setup with connection pooling options.

MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_DATABASE=devdb
MYSQL_USER=devuser
MYSQL_PASSWORD=your_secure_password
MYSQL_ROOT_PASSWORD=your_root_password
DATABASE_URL=mysql://devuser:your_secure_password@localhost:3306/devdb
DB_CONNECTION_LIMIT=20
DB_IDLE_TIMEOUT=300
ENVIRONMENT=development
chmod 600 .env.mariadb

Test MariaDB connection with environment variables

Verify the connection works by loading environment variables and connecting to the database.

set -a; source .env.mariadb; set +a
mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" -e "SELECT VERSION();"
mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" -e "SHOW TABLES;"

Database connection management and security

Create connection testing script

Build a utility script to test database connections across different environments.

#!/bin/bash

test_postgres() {
    echo "Testing PostgreSQL connection..."
    set -a; source .env.postgres; set +a
    if psql "$DATABASE_URL" -c "SELECT 1;" &>/dev/null; then
        echo "✓ PostgreSQL connection successful"
    else
        echo "✗ PostgreSQL connection failed"
        return 1
    fi
}

test_mariadb() {
    echo "Testing MariaDB connection..."
    set -a; source .env.mariadb; set +a
    if mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" -e "SELECT 1;" &>/dev/null; then
        echo "✓ MariaDB connection successful"
    else
        echo "✗ MariaDB connection failed"
        return 1
    fi
}

echo "=== Database Connection Tests ==="
test_postgres
test_mariadb
echo "=== Tests Complete ==="
chmod +x test-connections.sh

Create environment switcher script

Build a script to easily switch between different database environments during development.

#!/bin/bash

ENV_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

switch_environment() {
    local env_name="$1"
    local env_file="$ENV_DIR/.env.$env_name"
    
    if [ ! -f "$env_file" ]; then
        echo "Environment file $env_file not found"
        return 1
    fi
    
    # Create current environment symlink
    ln -sf "$env_file" "$ENV_DIR/.env.current"
    echo "Switched to $env_name environment"
    echo "Load with: set -a; source $ENV_DIR/.env.current; set +a"
}

list_environments() {
    echo "Available environments:"
    for env_file in "$ENV_DIR"/.env.*; do
        [ -f "$env_file" ] && basename "$env_file" | sed 's/^.env.//'
    done
}

case "$1" in
    list)
        list_environments
        ;;
    *)
        if [ -n "$1" ]; then
            switch_environment "$1"
        else
            echo "Usage: $0 {environment_name|list}"
            list_environments
        fi
        ;;
esac
chmod +x switch-env.sh

Configure connection pooling and security

Create a comprehensive configuration file that includes connection pooling and security settings.

# Database Security Configuration
DB_SSL_MODE=require
DB_SSL_CERT=/path/to/client-cert.pem
DB_SSL_KEY=/path/to/client-key.pem
DB_SSL_CA=/path/to/ca-cert.pem

Connection Pooling

DB_POOL_MIN_SIZE=5 DB_POOL_MAX_SIZE=20 DB_POOL_TIMEOUT=30 DB_POOL_IDLE_TIMEOUT=300

Query and Connection Timeouts

DB_CONNECT_TIMEOUT=10 DB_QUERY_TIMEOUT=30 DB_IDLE_IN_TRANSACTION_TIMEOUT=60

Application Security

ENVIRONMENT=development DEBUG=false LOG_LEVEL=info SECURE_COOKIES=true SESSION_TIMEOUT=1800

This configuration provides a foundation for secure database connections that can be customized for different environments. The PostgreSQL SSL encryption tutorial covers advanced security hardening, while the MariaDB monitoring setup helps track database performance across environments.

Verify your setup

# Test environment switching
./switch-env.sh list
./switch-env.sh postgres
set -a; source .env.current; set +a
echo "Database: $POSTGRES_DB on $POSTGRES_HOST:$POSTGRES_PORT"

Test database connections

./test-connections.sh

Verify PostgreSQL connection

psql "$DATABASE_URL" -c "\l"

Test MariaDB connection

./switch-env.sh mariadb set -a; source .env.current; set +a mysql -h"$MYSQL_HOST" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SHOW DATABASES;"

Check file permissions

ls -la .env.

Common issues

SymptomCauseFix
Environment variables not loadedMissing set -a before sourceset -a; source .env.file; set +a
PostgreSQL connection refusedService not running or wrong hostsudo systemctl status postgresql and check POSTGRES_HOST
MySQL access deniedWrong password or user permissionsReset password with mysql -u root -p and recreate user
Permission denied on .env filesFile permissions too restrictivechmod 600 .env. for owner read/write only
Database does not existDatabase not created or wrong nameCheck database name in environment file and recreate if needed
Scripts not executableMissing execute permissionchmod +x *.sh to make scripts executable

Next steps

Running this in production?

Want this handled for you? This works for a single server. When you run multiple environments or need this available 24/7, keeping it healthy is a different job. See how we run infrastructure like this for European teams.

Automated install script

Run this to automate the entire setup

Need help?

Don't want to manage this yourself?

We handle high availability infrastructure for businesses that depend on uptime. From initial setup to ongoing operations.