How to Fix the Invalid Interpolation Format Error in Docker Compose

We run into a strange error when we added a new environment variable to our Docker Compose file:

$ docker-compose up

ERROR: Invalid interpolation format for "environment" option in service "api": "MY_KEY=Abc$5"

Our docker-compose.yaml file looks like this:

version: "3.2"
services:
  db:
    image: mcr.microsoft.com/mssql/server:latest
    volumes:
        - ./container_db:/var/opt/mssql/data
    environment:
        ACCEPT_EULA: Y
        SA_PASSWORD: P@ssword123
    ports:
        - 6000:1433
  api:
    image:
        mcr.microsoft.com/dotnet/sdk:6.0
    volumes:
        - ./MinApi:/workspace
    working_dir: /workspace
    command: sh -c 'while true; do sleep 30; done'
    environment:
        - MY_KEY=Abc$5
    ports:
        - 7001:7000
    depends_on:
      - db

The problem is the $ in the value of the environment variable MY_KEY. Docker allows a lot of flexibility in its configuration files. One way to do that is to use variables. Unfortunately, in our case the $ is just a $ and not an indicator for a variable. It is basically the same problem we had a few years ago with DbUp.

We can escape the $ sign by using two $$ to prevent the variable substitution:

    environment:
        - MY_KEY=Abc$$5

With this change we can run docker-compose without any errors. Inside the container, our variable has the right number of $:

The env variable has only one $ sign.