Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 214 of 8023. Docker Orchestration and StorageFree lesson

Implementing Variable Interpolation in YAML

This lesson teaches how to use shell-style variable substitution to dynamically populate Docker Compose files based on the current deployment context.

In this lesson, you will learn how to make your Docker Compose files flexible by using shell-style variable interpolation to inject configuration values dynamically.

What is Variable Interpolation?

Hardcoding values like image tags, port numbers, or file paths inside a docker-compose.yml file makes your configuration rigid. It forces you to manually edit the file every time your deployment context changes (e.g., switching between development and production).

Variable interpolation allows you to use placeholders in your YAML that Docker Compose automatically replaces with values from your environment or a .env file at runtime. This allows you to write a single configuration file that adapts to its surroundings.

Using Interpolation in Action

To use interpolation, you reference variables using the $VARIABLE or ${VARIABLE} syntax directly within your YAML.

Imagine you have a docker-compose.yml file where you want to switch the application version easily:

services:
  web:
    image: my-app:${APP_VERSION:-latest}
    ports:
      - "${HOST_PORT}:80"

In this example:

  • ${APP_VERSION:-latest} tells Docker Compose: "Look for an APP_VERSION environment variable. If it doesn't exist, use latest as the default."
  • ${HOST_PORT} will be read directly from your shell environment or a .env file located in the same directory.

When you run docker-compose up, the tool scans these placeholders. If you have a .env file containing APP_VERSION=v2.1 and HOST_PORT=8080, Docker Compose substitutes them before starting your services, effectively deploying your specific version on your chosen port without you having to touch the YAML code.

Why use this?

This approach separates your infrastructure logic (the structure of your services) from your deployment data (the specific versions and environment settings). It prevents configuration drift and makes it significantly easier to manage multi-environment deployments, ensuring that your YAML files remain clean and reusable across different stages of your CI/CD pipeline.

Key Takeaway: By using ${VARIABLE} syntax in your Compose files, you decouple your configuration from your environment, allowing for dynamic, context-aware deployments without modifying your core infrastructure code.