← Back to Questions
Docker

Docker Compose environment variables explained

Learn Docker Compose environment variables explained with simple explanations, real-time examples, interview tips and practical use cases.

Docker Compose Environment Variables Explained

Docker Compose environment variables are used to configure containers dynamically without hardcoding values directly inside the application or Docker Compose file.

Environment variables are one of the most important concepts in:

  • Docker
  • Docker Compose
  • Microservices
  • Cloud-native applications
  • CI/CD pipelines
  • Production DevOps systems
Simple Definition: Environment variables allow applications running inside Docker containers to receive configuration values such as database URLs, passwords, API keys, ports, and profiles dynamically at runtime.

Why Environment Variables are Important

Applications behave differently across environments.

Environment Example Configuration
Development Local DB, debug mode
Testing Test database
Production Production DB, cloud secrets

Hardcoding values inside application code creates serious problems.

β€œApplications should be portable. Configuration should be external.”

Real-Time Production Example

Consider a production learning platform serving users from USA, UK, and India.

Services:

API Gateway
Portfolio Service
Interview Service
Payment Service
MySQL
Redis
    

Each service needs:

  • Database credentials
  • Service URLs
  • JWT secrets
  • Payment keys
  • OAuth credentials
  • Profiles

Environment variables manage these configurations securely and dynamically.

Basic Docker Compose Environment Variable Example

services:

  app:
    image: springboot-app
    environment:
      DB_HOST: mysql
      DB_PORT: 3306
      SPRING_PROFILES_ACTIVE: prod
    

Internal Environment Variable Flow

docker-compose.yml
       |
Environment Variables
       |
Docker Engine
       |
Container Environment
       |
Application Reads Values
    

How Applications Access Environment Variables

Spring Boot Example

spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
    

Java Example

System.getenv("DB_URL")
    

Node.js Example

process.env.DB_URL
    

Python Example

os.getenv("DB_URL")
    

Two Ways to Define Environment Variables

Method Description
Inline Variables Defined directly in Compose file
.env File External configuration file

Method 1: Inline Environment Variables

services:

  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: portfolio_db
    

Easy for small setups but not ideal for production secrets.

Method 2: Using .env File

Docker Compose automatically reads:

.env
    

.env Example

DB_USERNAME=root
DB_PASSWORD=securepassword
SPRING_PROFILES_ACTIVE=prod
MYSQL_ROOT_PASSWORD=securepassword
RAZORPAY_KEY_ID=rzp_live_xxxxx
RAZORPAY_KEY_SECRET=secret
    

Using Variables Inside Compose File

services:

  app:
    environment:
      DB_USERNAME: ${DB_USERNAME}
      DB_PASSWORD: ${DB_PASSWORD}
    

Environment Variable Resolution Flow

.env File
      |
Docker Compose Reads Variables
      |
Variables Injected into Containers
      |
Application Accesses Variables
    

Production Architecture

+------------------------------------------------------+
|                  Docker Compose                      |
|                                                      |
| docker-compose.yml                                   |
|        |                                             |
|        v                                             |
| .env File                                            |
|        |                                             |
|        v                                             |
| Containers                                            |
|        |                                             |
|        v                                             |
| Spring Boot / Node.js / Python Apps                  |
|                                                      |
+------------------------------------------------------+
    

Why .env Files are Better

  • Environment separation
  • Cleaner Compose files
  • Easy configuration changes
  • Better CI/CD integration
  • Improved portability

Production Best Practice

Never commit production .env files into Git repositories.

Use .gitignore

.env
.env.production
.env.secret
    

Common Production Environment Variables

Variable Purpose
SPRING_PROFILES_ACTIVE Application profile
DB_URL Database connection URL
DB_USERNAME Database username
DB_PASSWORD Database password
JWT_SECRET Authentication signing key
REDIS_HOST Redis connection

Microservices Environment Variable Example

services:

  api-gateway:
    image: api-gateway
    environment:
      PORTFOLIO_SERVICE_URL: http://portfolio-service:8080
      INTERVIEW_SERVICE_URL: http://interview-service:8082
      PAYMENT_SERVICE_URL: http://payment-service:8084

  portfolio-service:
    image: portfolio-service
    environment:
      DB_URL: jdbc:mysql://mysql:3306/portfolio_db

  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
    

How Service URLs Work

Docker Compose networking and DNS allow services to communicate using service names.

Service Communication Flow

API Gateway
      |
Environment Variable
      |
http://portfolio-service:8080
      |
Docker DNS Resolves Service
      |
Portfolio Service Container
    

Variable Substitution Syntax

Basic Syntax

${VARIABLE_NAME}
    

Default Value Syntax

${PORT:-8080}
    

Uses:

8080
    

if PORT variable is missing.

Example with Defaults

environment:
  SERVER_PORT: ${SERVER_PORT:-8080}
    

Required Variable Syntax

${DB_PASSWORD:?Database password required}
    

Docker Compose throws error if variable missing.

Using Multiple Environment Files

Different environments often use different files.

.env.dev
.env.test
.env.prod
    

Specify Environment File

docker compose --env-file .env.prod up -d
    

Environment File Architecture

Development -> .env.dev
Testing     -> .env.test
Production  -> .env.prod
    

Environment Variables vs Docker Secrets

Feature Environment Variables Docker Secrets
Ease of use Simple Moderate
Security Moderate High
Best for General config Sensitive secrets

Why Environment Variables are Not Fully Secure

Environment variables may be visible through:

  • docker inspect
  • Container process lists
  • Logs
  • Debugging tools

Highly sensitive secrets should use dedicated secret management systems.

Production Secret Management Options

  • Docker Secrets
  • HashiCorp Vault
  • AWS Secrets Manager
  • Azure Key Vault
  • Kubernetes Secrets

Environment Variables in CI/CD Pipelines

CI/CD systems inject variables dynamically during deployment.

CI/CD Flow

GitHub Actions / Jenkins
      |
Inject Environment Variables
      |
Docker Compose Deployment
      |
Containers Receive Config
    

Jenkins Example

docker compose \
  --env-file .env.prod \
  up -d
    

Spring Boot Production Example

services:

  api-gateway:
    image: api-gateway:1.0.0
    environment:
      SPRING_PROFILES_ACTIVE: prod
      DB_URL: jdbc:mysql://mysql:3306/gateway_auth
      DB_USERNAME: ${DB_USERNAME}
      DB_PASSWORD: ${DB_PASSWORD}
      GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
      GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET}
      JWT_SECRET: ${JWT_SECRET}
    

Container Startup Flow

Docker Compose Starts Container
       |
Environment Variables Injected
       |
Spring Boot Starts
       |
Reads Variables
       |
Application Configured
    

Environment Variables and Scaling

All scaled replicas receive the same environment variables.

Scaling Example

docker compose up -d --scale app=3
    

Scaled Environment Flow

App-1 -> Receives Variables
App-2 -> Receives Variables
App-3 -> Receives Variables
    

Debugging Environment Variables

Enter Container

docker exec -it app sh
    

View Variables

env
    

View Specific Variable

echo $DB_URL
    

Validate Final Compose Configuration

docker compose config
    

Shows fully resolved environment variables.

Common Environment Variable Problems

  • Missing .env file
  • Typo in variable name
  • Wrong variable substitution syntax
  • Variables not exported in shell
  • Secrets accidentally committed to Git

Environment Variable Precedence

Docker Compose resolves variables using priority order.

Typical Priority

CLI Variables
      |
Shell Variables
      |
.env File
      |
Default Values
    

Production Best Practices

  1. Use .env files
  2. Never hardcode secrets
  3. Use default values carefully
  4. Separate configs by environment
  5. Use secret managers for sensitive data
  6. Validate configuration before deployment
  7. Use meaningful variable names
  8. Keep application stateless

Production Environment Architecture

+------------------------------------------------------+
|                 Docker Compose                       |
|                                                      |
| docker-compose.yml                                   |
|        |                                             |
|        v                                             |
| .env.production                                      |
|        |                                             |
|        v                                             |
| Environment Variables                                |
|        |                                             |
|        v                                             |
| Containers                                            |
|        |                                             |
|        v                                             |
| Spring Boot / Node.js Apps                           |
|                                                      |
+------------------------------------------------------+
    

Interview Answer

Docker Compose environment variables are used to provide dynamic configuration values to containers at runtime. They allow applications to receive settings such as database URLs, credentials, service endpoints, API keys, and profiles without hardcoding them into source code or Docker images.

Environment variables can be defined inline inside docker-compose.yml or externally using .env files. Docker Compose automatically injects these values into containers during startup, and applications access them through their runtime environment.

In production systems, environment variables are essential for portability, CI/CD automation, environment separation, and secure configuration management.

Quick Summary Table

Feature Purpose
.env File External configuration
${VAR} Variable substitution
Default Values Fallback configuration
Service URLs Microservice communication
Secrets Authentication/security config

Useful Internal Links

Final Conclusion

Docker Compose environment variables provide flexible, portable, and scalable configuration management for containerized applications. They separate application code from environment-specific configuration, making deployments safer and easier across development, testing, and production environments.

Modern production systems rely heavily on environment variables combined with secret management, CI/CD pipelines, and cloud-native configuration practices to securely operate distributed microservices platforms at scale.

Why this Docker question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.