How to pass argument to docker-compose

Question:

import argparse
parser = argparse.ArgumentParser()

parser.add_argument(
    '--strat', 
    type=str, 
)
args = parser.parse_args()
strat = args.strat

I would like to right my docker-compose.yml file such as I would just pass my argument from there.
I did

version: "3.3"
services:
  mm:
    container_name: mm
    stdin_open: true
    build: .
       context: .
       dockerfile: Dockerfile
       args:
           strat: 1

and my docker file

FROM python:3.10.7

COPY . .

RUN pip3 install --upgrade pip
RUN pip3 install -r requirements.txt

CMD python3 main.py

But it does not work.

Any idea what I should change pelase?

Asked By: Nicolas Rey

||

Answers:

You need to update docker file to process the build arguments and remap them to environment variables to be processed by CMD. Try something like the following:

FROM python:3.10.7
ARG strat

# ...
ENV strat=${strat}
CMD python3 main.py --strat=$strat

But personally I would consider completely switching to environment variables instead of build arguments (so there is no need to rebuild image for every argument change).

Answered By: Guru Stron

The args thingy is for "build time" only.
If you want to run your already built image with different arguments, use environment variables or just pass them as you would with a regular binary.

like: docker compose run backend ./manage.py makemigrations
here you see that the ./manage.py and makemigrations are two arguments passed to backend service defined in docker-compose.yml

Answered By: tormich