skip to Main Content

I’m trying to pass 2 commands to Dockerfile to be executed one after another, but have had no luck since:
Dockerfile:

FROM alpine
ARG COMMAND
ENV COMMAND=${COMMAND}
CMD "${COMMAND}"

docker.compose.yml:

version: '3.7'

services:
  check_requirements:
    image: my_test_image
    build:
      args:
        COMMAND: "echo 1; echo 2"
      context: .
      dockerfile: Dockerfile

when I run docker compose build and then docker compose run test (or docker container run -it my_test_image) I get:

/bin/sh: echo 1; echo 2: not found

If I substitute last line of Dockerfile with:

CMD ["sh", "-c", "${COMMAND}"]

I get

1; echo 2

Expected:
on CMD Docker runs echo 1 and then echo 2

Is what I am trying to achieve possible?

2

Answers


  1. I’m trying to pass 2 commands a script to Dockerfile to be executed

    Sure, then write the script content to a file and execute.

    ARG COMMAND
    ENV COMMAND=${COMMAND}
    RUN printenv "$COMMAND" > /script.sh
    CMD ["sh", "/script.sh"]
    

    Or you can call eval to evaluate the content of an environment variable.

    ARG COMMAND
    ENV COMMAND=${COMMAND}
    CMD ["sh", "-c", "eval "$COMMAND""]
    
    Login or Signup to reply.
  2. You can just override the command when you run the container. You do not need to try to marshal it through an environment variable or build ARG.

    version: '3.8'
    services:
      check_requirements:
        build: .
        command: sh -c 'echo 1; echo 2'
    

    I’d suggest making the Dockerfile CMD be the "default" thing you expect a container to do. This is one of a couple of things I would not make parameterized; just declare a fixed CMD and allow it to be overridden when you run the container. (One specific example that comes to mind is a Python application where the default CMD runs a Django application but you can override Compose command: to run a Celery worker from the same code base.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search