# Environment Variables and YAML Anchors — Docker Compose

Source: https://www.skillbyai.com/en/docker-compose/s-env

> Configure services without repeating yourself.

## environment, env_file and x- extension fields

Pass configuration with `environment` (a map or list) or `env_file` (a file of KEY=VALUE lines). To share common settings, define them once in an **extension field** (a top-level key starting with `x-`) with a YAML **anchor** (`&common-env`) and merge it into services with `<<: *common-env`; keys listed after the merge override it. In the demo, web and api share TZ and LOG_LEVEL this way.

## The resolved web environment, run

I ran this with Docker Compose v2.38.1 and jq in the demo "shop" project. docker compose config parses, interpolates, merges and validates the files without starting containers; the Docker daemon was not running, so nothing was started. The web service's environment combines the anchored common values (TZ and LOG_LEVEL, which defaults to info) with its own API_URL.

```bash
docker compose config --format json | jq -c ".services.web.environment"
```

Output:

```
{"API_URL":"http://api:3000","LOG_LEVEL":"info","TZ":"Asia/Kolkata"}
```

## Keep secrets out of environment

Environment variables leak into logs and inspect output; use Compose secrets (files) for passwords and keys.

**Quiz:** What does <<: *common-env do?

- [ ] Creates a network
- [ ] Deletes common variables
- [ ] Starts a new service
- [x] Merges the mapping defined by the &common-env anchor into this mapping

*Answer:* Merges the mapping defined by the &common-env anchor into this mapping. Anchors avoid repetition.
