Home > Software engineering >  Using dollar symbol in docker compose build args confusion
Using dollar symbol in docker compose build args confusion

Time:03-11

When running docker compose I want to pass my user id and group id from my OS (Ubuntu 21.10). I do this so I can create a user that has a matching id in the container to the user I'm currently logged in as.

When I (in my php-apache container) specify build args as follows:

version: '3.8'

services:
  api_php-apache:
    container_name: api_php-apache
    build:
      args:
        USER_ID: ${(id -u)}
        GROUP_ID: ${(id -g)}

I receive the following error:

invalid interpolation format for services.api_php-apache.build.args.GROUP_ID: "${id -g}". You may need to escape any $ with another $.

But if I specify it like this:

version: '3.8'

services:
  api_php-apache:
    container_name: api_php-apache
    build:
      args:
        USER_ID: ${UID}
        GROUP_ID: ${GID}

and I have exported my id -u and id -g in my ~/.bashrc it passes the id's correctly to the command.

How can I achieve this id -u/id -g command that passes the syntax correctly?

MY DOCKER-COMPOSE.YML

version: '3.8'

services:
  api_php-database:
    image: postgres
    container_name: api_php-database
    restart: unless-stopped
    environment:
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: laravel_docker
    volumes:
      - ./postgres-data:/var/lib/postgresql/data
    ports:
      - '5432:5432'
  api_php-apache:
    container_name: api_php-apache
    build:
      context: ./php
      args:
        USER_ID: ${(id -u)}
        GROUP_ID: ${(id -g)}
    ports:
      - '8080:80'
    volumes:
      - ./src:/var/www/laravel_docker
      - ./apache/default.conf:/etc/apache2/sites-enabled/000-default.conf
    depends_on:
      - api_php-database

CodePudding user response:

You cannot use a subshell inside the compose.yaml. You need to export those before you run compose, and then just reference the variable or leave it empty so compose will pick it up.

api_php-apache:
  container_name: api_php-apache
  build:
    context: ./php
    args:
      USER_ID: ${USER_ID:-1000}
      GROUP_ID: ${GROUP_ID:-1000}
export USER_ID="$(id -u)"
export GROUP_ID="$(id -g)"
docker compose up --build

The way I did it here, it will fall back to uid and gid 1000 if it wasn't set in the .env file or the current shell.

  • Related