Configuring Environment Variables and Service Dependencies
In multi-container applications, backend services often require configuration variables (such as database credentials), and must wait for database containers to start before initializing.
1. Injecting Environment Variables
You can define environment variables directly inside your docker-compose.yml file using either key-value syntax or list syntax:
services:
web-app:
image: node:20-alpine
environment:
- NODE_ENV=production
- API_PORT=3000Loading Variables from .env Files
To keep credentials secure, avoid hardcoding them in your Compose file. Instead, save them in a .env file in the same directory. Docker Compose loads these variables automatically:
# .env
DB_USER=admin
DB_PASSWORD=supersecret# docker-compose.yml
services:
database:
image: postgres:alpine
environment:
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}2. Managing Startup Order with depends_on
If your API server starts before your database is ready, the API server will crash. Use the depends_on directive to define the startup order:
services:
database-server:
image: postgres:alpine
environment:
POSTGRES_PASSWORD: password
api-server:
image: my-api:latest
depends_on:
- database-server # Start database-server container before starting api-serverNote: depends_on only controls the startup order of the containers; it does not check if the application inside the container is fully initialized and ready. To ensure a database is ready to accept connections before starting dependent containers, configure a healthcheck block.