Pass parameters to docker-compose command

Viewed 657

I have Dockerfile:

FROM python:3.8

ARG CMD_ARGS=$CMD_ARGS
ENV PYTHONUNBUFFERED 1

COPY ./requirements.txt /requirements.txt
RUN pip install -r /requirements.txt

RUN mkdir /app
COPY . /app
WORKDIR /app

And Docker-compose.yml file:

version: '3'

services:
  selenium:
    image: selenium/standalone-chrome
    ports:
    - 4444:4444
    restart: always

  app:
    build:
      context: .
    volumes:
    - .:/app
    command: sh -c "python3 my_script.py -arg1 -arg2"
    depends_on:
      - selenium

Is there a way not to hardcode arg1,arg2 in docker-compose.yml file and instead pass it in docker-compore up command OR using environmental variables (args containing whitespace characters) somehow?

1 Answers

You can try Variable substitution for your case.

example from docs:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

If an environment variable is not set, Compose substitutes with an empty string. In the example above, if POSTGRES_VERSION is not set, the value for the image option is postgres:.

or for passing variable to command You can use $$.

You can use a $$ (double-dollar sign) when your configuration needs a literal dollar sign. This also prevents Compose from interpolating a value, so a $$ allows you to refer to environment variables that you don’t want processed by Compose.

example:

app:
  command: sh -c "python3 my_script.py $$VAR_ARG_1"

and on cli, You need to set VAR_ARG_1 variable.

Related