Iterate in RUN command in Dockerfile

It looks like you're using backticks. What's in backticks gets executed and the text in the backticks gets replaced by what's returned by the results.

Try using single quotes or double quotes instead of backticks.

Try getting rid of the backticks like so:

RUN for i in x y z; do echo "$i"; done

I would suggest an alternative solution of this.

In stead of having the LOOP inside docker file, can we take a step back ...

Implement the loop inside a independent bash script;

Which means you would have a loop.sh as following:

#!/bin/bash

for i in $(seq 1 5); do echo "$i"; done

And in your Dockerfile, you will need to do:

COPY loop.sh loop.sh
RUN ./loop.sh

This will take one extra step and cost one more layer. However, if you need to do more stuff, I would recommend to put them all into the script. And whatever operations you put in the script will only cost one layer.

This approach is could be cleaner and more maintainable.

Please also have a read at this one: https://hackernoon.com/tips-to-reduce-docker-image-sizes-876095da3b34


For a more maintainable Dockerfile, my preference is to use multiple lines with comments in RUN instructions especially if chaining multiple operations with &&

RUN sh -x \
    #
    # execute a for loop
    #
    && for i in x  \
                y  \
                z; \
       do \
              echo "$i"
       done \
    \
    #
    # and tell builder to have a great day
    #
    && echo "Have a great day!"